Search code examples
ruby-on-railsrubyhas-and-belongs-to-many

Rails HABTM ActiveRecord::RecordNotFound in update action


I have set an association using HABTM with Rails, with two models: Site and User.

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

View: sites/_form.html.slim

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

Now when I'm trying to update a Site, associating some User to it, I got the following error:

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.

This is strange, because I don't understand when does Rails is looking for those Site ids, which are actually supposed to be User ids. Site id appears to be correct in the params:

Params of the request

{"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"}

Something is going wrong, obviously ! Any idea ? Thanks


Solution

  • You have your class_name keys backwards.

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

    You don't need to have the class_name attribute on the User model as Rails can infer the Site class.

    Rails has very extensive documentation for relations.