现在有两张表 categories 和 stores,多对多关系。使用的是 simple_form 的 association
# category.rb
class Category < ActiveRecord::Base
has_many :store_store_categories
has_many :stores, through: :store_store_categories
end
# store.rb
class Store < ApplicationRecord
has_many :store_store_categories
has_many :categories, through: :store_store_categories
end
# store_store_category.rb
class StoreStoreCategory < ApplicationRecord
belongs_to :store
belongs_to :category
end
# store_category.rb
class StoreCategory < Category
end
# store_categories_controller.rb
def allow_params
params.require(:store_category).permit(:name, store_ids: [])
end
# stores_controller.rb
def store_params
params.require(:store).permit(:store_name, category_ids: [])
end
# app/views/stores/_form.html.erb
<%= simple_form_for @store, class: "form-horizontal" do |f| %>
<div class="row">
<div class="col-sm-2" style="text-align: right;">
<label>选择门店分组</label>
</div>
<div class="col-sm-2">
<%= f.association :categories, as: :check_boxes, class: "form-control", label: false %>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-sm-offset-2">
<%= link_to '返回', stores_path, class: "btn btn-white" %>
<input class="btn btn-primary" type="submit" name="commit" value="保存" data-disable-with="保存中。。。">
</div>
</div>
<% end %>
这个页面显示正常
![](https://l.ruby-china.com/photo/2017/5faae1348d08d731639dfe4db7e34c2f.png!large)
<%= simple_form_for @store, class: "form-horizontal" do |f| %>
<div class="row">
<div class="col-sm-2" style="text-align: right;">
<label>选择门店分组</label>
</div>
<div class="col-sm-2">
<%= f.association :categories, as: :check_boxes, class: "form-control", label: false %>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-sm-offset-2">
<%= link_to '返回', stores_path, class: "btn btn-white" %>
<input class="btn btn-primary" type="submit" name="commit" value="保存" data-disable-with="保存中。。。">
</div>
</div>
<% end %>
这个页面显示就变这样了