Rails 4 : Exception Site(#70058148983820) expected, got String(#8388700)


#1

I have a form with a selectbox which allow to select differents values. When I want to save the form I have an exception :

ActiveRecord::AssociationTypeMismatch at xxxxxxxxxxxxxxxxxxxxx
Site(#70058148983820) expected, got String(#8388700)

Here is the form which generate the select box

col-md-9
 .input-group.btn-group
    %span.input-group-addon
    =t('activerecord.attributes.user.volunteer_wishes_sites')
    = f.collection_select :wishes_sites, @sites, :id, :name, {:selected => @user.wishes_sites.map(&:id)}, {:multiple => true, :class=>"sites_multiselect"}

In my controller I have

def user_params
  params.require(:user).permit(
    :wishes_sites =>[],
  )
end

The model

class User < ActiveRecord::Base
  ....
  has_and_belongs_to_many :wishes_sites, :class_name => "Site", :join_table => :wishes_sites
end

here is the line which produces the bug

if @user.update_attributes(user_params)

Here are the migration

create_table :sites, force: true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.text     "address"
  t.text     "description"
end

create_table :wishes_sites, id: false, force: true do |t|
  t.integer "user_id"
  t.integer "site_id"
end

Thanx for your help


#2

Did you make sure the foreign key is the id for the model generated by rails and not one of the parameters you have? Parameters are not allowed for foreign keys. And how do you have a User model and controller without any schema table? I would delete all the User stuff and do in terminal rails g scaffold User name:string to make sure the schema table is the same User and then make sure all your foreign keys which you set (with more migrations which add columns) are only the model id’s and not parameters. Also while rebuilding the User from the scaffold make sure the strong parameters are ok. It looks like you know what you are doing; I’ve never worked with this association. If you accidentally made a foreign key a parameter you need to delete everything and rebuild it; and you can’t delete or edit migrations because they are scripts; so run in terminal rails destroy migration [full migration name, no extension]. Then to be clear rename the destroyed migrations with prefix destroyed-13423482u349832… in case they cause bugs rather than deleting the file.