【问题标题】:Getting undefined method for ActiveRecord::Relation获取 ActiveRecord::Relation 的未定义方法
【发布时间】:2012-01-13 09:52:58
【问题描述】:

我有以下型号

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

【问题讨论】:

  • 您能否再次检查并确认Chapter 有一个数据库列book_id,并且您的数据库已通过rake db:migrate 正确迁移?
  • 请显示您的编辑控制器方法,其中@chapter 已初始化

标签: ruby-on-rails activerecord


【解决方案1】:

看起来@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])

【讨论】:

  • 这很奇怪,所以where 会返回一个集合,即使只返回一条记录。附加first 修复它。
  • @JosephLeBrech 如果您从 id 中查找单个 ActiveRecord,通常可以使用 @chapter = Chapter.find(params[:id])
  • 我即将对其进行更改,使其执行类似于Books.find(params[:book_id]).chapters.where(:chapter_no =&gt; params[:chapter_no]).first 的操作,因为我希望用户能够重新排序章节并且必须以这种方式访问​​它们。所以我把它改成不使用 find
  • 其实在这里你可以稍微简化一下以减少对数据库的查询,这样:Chapter.where(:book_id =&gt; params[:book_id], :chapter_no =&gt; params[:chapter_no]).first
  • 在 Rails 4 中,不推荐使用动态查找器。所以,我用我所有的动态查找器换了.where(),但后来遇到了这个问题。因此,如果您将动态查找器替换为 .where(),请务必同时包含 .first
【解决方案2】:

正如其他人所说 - 添加 .first 方法将解决此问题。我在通过其唯一 ID 调用 @chapter 时遇到了这个问题。添加.first(或Rails 4 中的.take)将确保只返回一个对象。

【讨论】:

    【解决方案3】:

    试试:Chapter.find(params[:id]).first

    【讨论】:

      【解决方案4】:

      我遇到了类似的错误

      Books.chapters
      NoMethodError: undefined method `chapters' for #<Book::ActiveRecord_Relation:0x00007f8f9ce94610>
      

      我需要的是:

      Books.includes(:chapters)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        • 2013-12-16
        • 1970-01-01
        • 1970-01-01
        • 2015-08-09
        • 2013-08-06
        相关资源
        最近更新 更多