Ruby-on-rails 获取 ActiveRecord::Relation 的未定义方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8848657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:37:10  来源:igfitidea点击:

Getting undefined method for ActiveRecord::Relation

ruby-on-railsactiverecord

提问by Joseph Le Brech

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/idI get

/chapters/edit/id我得到

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

when i try to access book like this

当我尝试访问这样的书时

@chapter.book

回答by alony

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

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

@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

然后你会得到一个 Relation 对象(它可以被视为一个集合,但不是一个单一的对象)。因此,要解决此问题,您需要使用 检索记录find_by_id,或从集合中获取第一个记录

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

or

或者

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

回答by Jason

As the others have said - adding the .firstmethod will resolve this. I have experienced this issue when calling a @chapter by it's unique ID. Adding .first(or .takein Rails 4) will ensure only one object is returned.

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

回答by hellion

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

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