Rails HABTM ActiveRecord::RecordNotFound 正在更新操作

Rails HABTM ActiveRecord::RecordNotFound in update action

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

Site.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"

User.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 class.

Rails有非常extensive documentation的关系。