0

Let me clarify my question. I'm trying to get an integer value from @student.rooms.last, and it doesn't seem that @student.rooms.last alone will give me an integer value.

Student.transaction do
if @student.test!
 x = @student.site_id.to_int
 y = @student.rooms.last

book = Book.find(:first, :conditions => ["location_id = ? AND room_id = ?", x, y])

   room = Room.new
   room.student_id = @student.id 
   if room.save
     book.room_id = room.id

Right now this returns an error: You have a nil object when you didn't expect it! The error occurred while evaluating nil.room_id= I'm trying to find the room record associated with @student that has an id equal to the book room_id foreign key. Thanks for any response.

2
  • 1
    Why are you iterating over @student.rooms just to get the last element? I mean, why can't you just get the last element directly? Commented Feb 7, 2010 at 20:05
  • What difference is it whether you choose the first or last from a list if you don't tell Rails how you want the items ordered? Commented Feb 7, 2010 at 22:19

1 Answer 1

4

I imagine is the issue that z only exists in the block scope, and needs to be defined outside.

rooms = @student.rooms
z = nil
rooms.each do |room|
  if room.id == @student.rooms.length - 1
  z = room.id
end
end
book = Book.find(:first, :conditions => ["room_id = ?", z])

Really, though, why aren't you doing:

book = @student.rooms.last.books.first

? From my vague understanding of your script, it seems like it's the same thing.

And it almost feels like your code would break if the books belonged to students other than your first one, since @student.rooms.length - 1 would only be the ID of that student's last book if, say, the student owned 5 books with IDs 1-4... no, wait. That code should return the second-to-last book, right? And only if the student owns the very first books in the database?

Bah, whatever. Just use classic ActiveRecord methods.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.