新手问题 多对多使用 simple_form_for 问题

tt12580-github · 2017年03月28日 · 最后由 tt12580-github 回复于 2017年03月29日 · 1338 次阅读

现在有两张表 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 %>

这个页面显示就变这样了

试一下下面这种方法呢?可以自定义显示的内容。 f.association :company, label_method: :company_name, value_method: :id, include_blank: false

tesla_lee 回复

可以了 谢谢

tt12580-github 关闭了讨论。 03月29日 11:53
需要 登录 后方可回复, 如果你还没有账号请 注册新账号