views:

148

answers:

3

Hey all,

I edited this message do to sloppiness and changes.

def student_test
@student = Student.for_test.find(params[:id]) if params[:id]
@student ||= Student.new
run_sequence :testize
end

def test_finalize
Student.transaction do
if (params[:student]) and @student.update_attributes(params[:student])
  @student.test!
end

room = Room.new(:room_num => 5)
room.save

book = @student.books
book.id_num = room.id
book.save
end
end

This returns this error message: undefined method `id_num='

Is this because there is more than 1 book record being passed into book?

Any suggestions? Thanks.

+1  A: 

You have horrible unreadable style. I tried to clear a little what I could.

def student_test
  @student = Student.for_test.find(params[:id]) if params[:id]
  @student ||= Student.new
  run_sequence :testize
end

def test_finalize
  Student.transaction do
    if (params[:student]) and @student.update_attributes(params[:student])
      @student.test!
    end

    room = Room.new(:room_num => 5)
    room.save

    book = @student.book
    book.id_num = room.id
    book.save
  end
end

Your main problem was that named scopes are like finders - you don't write @student.find(:first), but write Student.find(:first). Same here - named scope is for retrieving object from DB, to add conditions ans rest to query. And then you call finder to get objects you wanted which.

I don't know flow of your program, but I suppose that test_finalize is run from student_test, so it can use @student.

MBO
+1  A: 

Well, what Ruby is trying to tell you is that the Book class doesn't have an accessor to write to the id_num attribute. But since it seems likely that we're talking about Active Record here, and Book actually points to a database table -- I hate to suggest the obvious, but is id_num a real field in the books table?

Of course, the Ruby error may be entirely unhelpful, and something else is going on.

Perhaps you could show us a little more context? Where does this code live? What is the data structure? (Oh, and without wishing to be rude -- please consider indenting your code!)

Shadowfirebird
+2  A: 

Assuming Student has a has_many relationship to Book, then @student.books is returning an array of book records, so you'll need the following:

books = @student.books
books.each do |book|
  book.id_num = room.id
  book.save
end
Mike Sutton
+1 for formidable ESP
glenn jackman
Yeah, that would fit perfectly, wouldn't it? book doesn't have an id_num attribute ... because it's an array.
Shadowfirebird
Thanks, that was the problem.
JohnMerlino
@shadowfirebird - it's an array of Book records, each of which has an id_num attribute
Mike Sutton
That's exactly my point. 'book.id_num' isn't valid; 'book[0].id_num' is -- in the original code, not yours.
Shadowfirebird