gpt4 book ai didi

ruby-on-rails - 更新操作中的 Rails HABTM ActiveRecord::RecordNotFound

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:39 25 4
gpt4 key购买 nike

我已经使用 HABTM 和 Rails 建立了一个关联,有两个模型:站点和用户。

网站.rb

  has_and_belongs_to_many :fae_users,
class_name: "Site",
foreign_key: "site_id",
join_table: "sites_users",
association_foreign_key: "fae_user_id"

用户.rb

    has_and_belongs_to_many :sites,
class_name: "User",
foreign_key: "fae_user_id",
join_table: "sites_users",
association_foreign_key: "site_id"

Schema.rb

  create_table "sites_users", id: false, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
t.bigint "site_id"
t.bigint "fae_user_id"
t.index ["fae_user_id"], name: "index_sites_users_on_fae_user_id"
t.index ["site_id"], name: "index_sites_users_on_site_id"
end

查看:sites/_form.html.slim

= f.collection_select :fae_user_ids, Fae::User.all, :id, :email, {}, {:multiple => true}

现在,当我尝试更新站点,将一些用户关联到它时,出现以下错误:

ActiveRecord::RecordNotFound in Admin::SitesController#update
Couldn't find all Sites with 'id': (3, 2) (found 1 results, but was looking for 2). Couldn't find Site with id 2.

这很奇怪,因为我不明白 Rails 什么时候在寻找那些实际上应该是用户 ID 的站点 ID。站点 ID 在参数中似乎是正确的:

请求参数

{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"xxxxxxxxxxxx",
"site"=>
{"site_status_id"=>"4",
"fae_user_ids"=>["", "3", "2"],
"prod_url"=>"",
"demo_url"=>"",
"template"=>"",
"name"=>"Somesite",
"site_option_ids"=>[""],
"description"=>"",
"domain"=>"",
"discount"=>""},
"id"=>"10"}

显然出了点问题!任何想法 ?谢谢

最佳答案

你的 class_name 键是倒过来的。

has_and_belongs_to_many :fae_users,
class_name: 'Fae::User'

has_and_belongs_to_many :sites

您不需要在 User 模型上具有 class_name 属性,因为 Rails 可以推断出 Site 类。

Rails 非常 extensive documentation关系。

关于ruby-on-rails - 更新操作中的 Rails HABTM ActiveRecord::RecordNotFound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54626061/

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