Gerrit
Gerrit

Reputation: 2677

ActiveRecord::AssociationTypeMismatch while updating model

I try to uodate a model by posting a form to the update method. The scenario is that we have clubs and each club belongs to a region.

The model is:

class Region < ActiveRecord::Base
    has_many :club
end

class Club < ActiveRecord::Base
    belongs_to :region
end

My view uses to create the form select element:

<%= f.collection_select(:region, Region.all, :id, :caption, {}, {class: "form-control"} ) %>

And my controller looks like this

def update
    @club = Club.find(params[:id])
    if @club.update(club_params)
        redirect_to @club
    else
        render 'edit'
    end
end

THe param region is permitted. Where is my mistake?

Thanks

Upvotes: 0

Views: 505

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51171

It should be region_id instead of region (also in club_params implementation):

<%= f.collection_select(:region_id, Region.all, :id, :caption, {}, {class: "form-control"} ) %>

From your comment I guess you should also generate migration adding region_id column to your clubs table:

bundle exec rails g migration add_region_id_to_clubs region:references

and run it:

bundle exec rake db:migrate

Upvotes: 0

Related Questions