小编age*_*ith的帖子

Rails has_many:through和collection_select有多个

我使用has_many有以下问题:通过collection_select在multi-select中通过多对多关系:multiple => true.我有供应商提供许多成分,可由许多供应商提供.看一看:

成分模型:

class Ingredient < ActiveRecord::Base
  has_many :ingredient_suppliers
  accepts_nested_attributes_for :ingredient_suppliers, :allow_destroy => true

  has_many :suppliers, :through => :ingredient_suppliers
end
Run Code Online (Sandbox Code Playgroud)

供应商模型:

class Supplier < ActiveRecord::Base
  has_many :ingredient_suppliers
  has_many :ingredients, :through => :ingredient_suppliers
end
Run Code Online (Sandbox Code Playgroud)

关系实体:

class IngredientSupplier < ActiveRecord::Base
  belongs_to :ingredient
  belongs_to :supplier
end
Run Code Online (Sandbox Code Playgroud)

这就是形式.请注意,如果不指定:name,我无法使其工作:

<%= form_for(@ingredient) do |f| %>
 <%= f.fields_for :suppliers do |supplier_fields| %>
      <%= supplier_fields.collection_select (:supplier_ids, 
            Supplier.all(:order=>"name ASC"), 
            :id, :name, 
            {:selected => @ingredient.supplier_ids, 
             :include_blank => true}, 
            {:multiple => true, 
              :name => 'ingredient[supplier_ids]'}) %>
  <% end %>
<% …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails

19
推荐指数
1
解决办法
1万
查看次数

标签 统计

ruby-on-rails ×1