Jos*_*ech 23 activerecord ruby-on-rails
我有以下型号
class Book < ActiveRecord::Base
  has_many :chapters
end
和
class Chapter < ActiveRecord::Base
    belongs_to :book
end
在/chapters/edit/id我得到
undefined method `book' for #<ActiveRecord::Relation:0x0000010378d5d0>
当我试图访问这样的书
@chapter.book
alo*_*ony 57
看起来@chapter不是一个章对象.如果@chapter初始化如下:
@chapter = Chapter.where(:id => params[:id])
然后你得到一个Relation对象(可以将其视为集合,但不是单个对象).因此,要解决此问题,您需要使用find_by_id或从集合中获取第一个记录来检索记录
@chapter = Chapter.where(:id => params[:id]).first
要么
@chapter = Chapter.find_by_id(params[:id])
正如其他人所说 - 添加该.first方法将解决此问题。我在通过 @chapter 的唯一 ID 调用它时遇到了这个问题。添加.first(或.take在 Rails 4 中)将确保只返回一个对象。
| 归档时间: | 
 | 
| 查看次数: | 37634 次 | 
| 最近记录: |