gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:04:56 24 4
gpt4 key购买 nike

我有以下型号

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 不是一个单独的 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])

关于ruby-on-rails - 获取 ActiveRecord::Relation 的未定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8848657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com