Rails has_many:through和collection_select有多个

age*_*ith 19 ruby-on-rails

我使用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 %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

如果我删除:name,那么我收到此错误消息:

Supplier(#-617951108) expected, got Array(#-608411888)

Request

Parameters:

{"commit"=>"Anlegen",
 "authenticity_token"=>"MuEYtngwThharmM1KaAbH8JD3bScXiDwj0ALMytxl7U=",
 "_method"=>"put",
 "utf8"=>"?",
 "id"=>"1",
 "ingredient"=>{"name"=>"Ingredient 1",
 "nr"=>"00100",
 "unit"=>"kg",
 "mol_per_unit"=>"2000,
00000",
 "description"=>"",
 "suppliers"=>{"supplier_ids"=>["1",
 "2"]}}}
Run Code Online (Sandbox Code Playgroud)

现在的问题是,PUT参数只包含一个supplier_id而不是一个supplier_id数组:

"ingredient"=>{"name"=>"Rohstoff 3", "nr"=>"00300", "unit"=>"Stk.", "mol_per_unit"=>"0,00000", "description"=>"", "supplier_ids"=>"2"}
Run Code Online (Sandbox Code Playgroud)

age*_*ith 37

我已经解决了问题.在这种情况下,使用fields_for是错误.解决方案是使用collection_select,如下所示:

<%= collection_select(:ingredient, :supplier_ids, 
              Supplier.all(:order=>"name ASC"), 
              :id, :name, {:selected => @ingredient.supplier_ids, :include_blank => true}, {:multiple => true}) %>
Run Code Online (Sandbox Code Playgroud)

  • 你是否必须在控制器中运行任何类型的构建.你能用控制器和视图的完整代码更新你的答案吗? (5认同)