views:

137

answers:

1

Ok this worked:

Student.transaction do
if @student.test!
 y = @student.rooms.first

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

It's strange. I wanted to get the last record not first, yet it thought first was the last and worked. Not sure why.

+5  A: 

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.

Matchu