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

时间:2019-02-11 07:52:12

标签: ruby-on-rails ruby has-and-belongs-to-many

我已经使用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。 网站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"}

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

1 个答案:

答案 0 :(得分:0)

您将class_name键向后移。

User

您不需要在Site模型上具有{{1}}属性,因为Rails可以推断{{1}}类。

Rails的关系非常extensive documentation