开发者

undefined method error

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_se开发者_运维百科quence :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.


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


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.


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!)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜