gpt4 book ai didi

ruby-on-rails - 无法通过关联找到没有带有 has_many 的 ID 的 [model]

转载 作者:太空宇宙 更新时间:2023-11-03 17:52:02 24 4
gpt4 key购买 nike

我有 3 个模型 - 妈妈、爸爸和 child 。爸爸妈妈只通过 child 属于彼此,所以关联是这样的:

class Kid < ActiveRecord::Base
belongs_to :mom
belongs_to :dad
end

class Mom < ActiveRecord::Base
has_many :kids
has_many :dads, through: :kids
end

class Dad < ActiveRecord::Base
has_many :kids
has_many :moms, through: :kids
end

我试图通过搜索任何妈妈而不只是通过爸爸的 child 找到爸爸的妈妈:

http://localhost:3000/dads/superdad/moms

resources :dads do
resources :kids
resources :moms
end

在我的 Moms Controller 中,我试图找到“superdad”的 ID:

def index
@dad = Dad.find(params[:id])
if params[:q].present?
@moms = Mom.search(params[:q], page: params[:page], per_page: 25)
else
@moms = Mom.none
end
end

但是遇到这个错误:

Couldn't find Dad without an ID  
# line 8 @dad = Dad.find(params[:id])

当 Mom 没有直接 id 时,是否可以以这种方式使用 @dad?你建议我做什么?我需要在妈妈的索引页面上访问@dad.name(以及更多)。

最佳答案

使用这个:

def index
@dad = Dad.find(params[:dad_id])
if params[:q].present?
@moms = Mom.search(params[:q], page: params[:page], per_page: 25)
else
@moms = Mom.none
end
end

使用 params[:dad_id] 而不是 params[:id]。原因是为 MomsController 的索引操作生成的路由将是:

dad_moms GET    /dads/:dad_id/moms(.:format)          moms#index

params[:dad_id] 会从 http://localhost:3000/dads/superdad 给你 dad_id 作为 superdad/妈妈们。在您的情况下,您正在寻找不存在的 params[:id] 。因此,错误。

关于ruby-on-rails - 无法通过关联找到没有带有 has_many 的 ID 的 [model],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22896237/

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