2011-11-23 15 views
19

私は、collection_select:multiple => trueを使用して、複数選択でhas_many:many-to-manyリレーションを使用して次の問題を抱えています。私は、多くのサプライヤーが提供できる多くの成分を提供するサプライヤーを抱えています。見てください:Rails has_many:throughとmultipleを指定したcollection_select

Ingredientモデル:

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

    has_many :suppliers, :through => :ingredient_suppliers 
end 

サプライヤーモデル:

class Supplier < ActiveRecord::Base 
    has_many :ingredient_suppliers 
    has_many :ingredients, :through => :ingredient_suppliers 
end 

関係エンティティ:

class IngredientSupplier < ActiveRecord::Base 
    belongs_to :ingredient 
    belongs_to :supplier 
end 

そして、これはフォームです。名前:私はそれを指定せずに動作させることができなかったことに注意してください

<%= 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 %> 

私は削除する場合:、今は

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"]}}} 

問題という:名前を、私は、このエラーメッセージが表示されますPUTパラメータにはsupplier_idの配列の代わりにsupplier_idが1つだけ含まれています。

"ingredient"=>{"name"=>"Rohstoff 3", "nr"=>"00300", "unit"=>"Stk.", "mol_per_unit"=>"0,00000", "description"=>"", "supplier_ids"=>"2"} 
+0

コントローラのコードを表示できますか? – Skiapex

答えて

36

問題が解決しました。この場合、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}) %> 
+5

あなたはどんな種類のビルドもコントローラで実行しなければなりませんでしたか?コントローラーとビューのフルコードで回答を更新できますか? –

関連する問題