未定义的方法错误

我把这条消息编辑成了邋and和变化。

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 

这将返回此错误消息:undefined method`id_num =’

这是因为有超过1本书记录被传入书中吗?

有什么建议? 谢谢。

假设学生与Book有一个has_many关系,那么@ student.books将返回一系列书籍记录,因此您需要以下内容:

 books = @student.books books.each do |book| book.id_num = room.id book.save end 

你有一种可怕的难以理解的风格。 我试着清楚一点我能做些什么。

 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 

你的主要问题是命名的范围就像查找程序 – 你不写@student.find(:first) ,但写了Student.find(:first) 。 同样在这里 – 命名范围用于从DB检索对象,添加条件和rest以进行查询。 然后你调用finder来获取你想要的对象。

我不知道你的程序的流程,但我想test_finalize是从student_test运行的,所以它可以使用@student。

好吧,Ruby试图告诉你的是,Book类没有写入id_num属性的访问器。 但是因为我们在这里谈论Active Record似乎很可能,并且Book实际上指向了数据库表 – 我讨厌建议显而易见的,但是id_num是书表中的真实字段吗?

当然,Ruby错误可能完全没有用,还有其他事情正在发生。

也许你可以告诉我们更多的背景? 这段代码住在哪里? 什么是数据结构? (哦,不希望变得粗鲁 – 请考虑缩进你的代码!)