获取未定义的方法的ActiveRecord ::关系关系、未定义、方法、ActiveRecord

2023-09-09 22:07:13 作者:别人假正经我却假不正经

我有以下型号

 类图书<的ActiveRecord :: Base的
  的has_many:章节
结束
 

 班章<的ActiveRecord :: Base的
    belongs_to的:书
结束
 

/章节/编辑/ ID 我收到

 未定义的方法'书'的#<的ActiveRecord ::关联:0x0000010378d5d0>
 
错误 无法获取属性 clientWidth 的值 对象为null或未定义

当我尝试访问的书像这样

  @ chapter.book
 

解决方案

看起来@chapter不是一个单独的章节对象。如果@chapter初始化是这样的:

  @chapter = Chapter.where(:ID => PARAMS [:ID])
 

则得到一个关联对象(可以被视为一个集合,但不是一个单一的对象)。所以,你需要使用检索记录 find_by_id ,或采取从集合的第一个来解决这个问题。

  @chapter = Chapter.where(:ID => PARAMS [:ID])。第一
 

  @chapter = Chapter.find_by_id(PARAMS [:ID])
 

I have the following models

class Book < ActiveRecord::Base
  has_many :chapters
end

and

class Chapter < ActiveRecord::Base
    belongs_to :book
end

in /chapters/edit/id I get

undefined method `book' for #<ActiveRecord::Relation:0x0000010378d5d0>

when i try to access book like this

@chapter.book

解决方案

Looks like @chapter is not a single Chapter object. If @chapter is initialized something like this:

@chapter = Chapter.where(:id => params[:id])

then you get a Relation object (that can be treated as a collection, but not a single object). So to fix this you need to retrieve a record using find_by_id, or take a first one from the collection

@chapter = Chapter.where(:id => params[:id]).first

or

@chapter = Chapter.find_by_id(params[:id])