更新模型时ActiveRecord :: AssociationTypeMismatch

时间:2014-04-01 13:12:53

标签: ruby-on-rails activerecord ruby-on-rails-4

我尝试通过将表单发布到update方法来修改模型。场景是我们有俱乐部,每个俱乐部属于一个地区。

模型是:

class Region < ActiveRecord::Base
    has_many :club
end

class Club < ActiveRecord::Base
    belongs_to :region
end

我的视图用于创建表单选择元素:

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

我的控制器看起来像这样

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

允许param区域。我的错误在哪里?

由于

1 个答案:

答案 0 :(得分:0)

应该是region_id而不是region(也在club_params实施中):

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

根据您的评论,我猜您还应该生成将region_id列添加到clubs表格的迁移:

bundle exec rails g migration add_region_id_to_clubs region:references

并运行它:

bundle exec rake db:migrate