Подтвердить что ты не робот

Rails has_many: through и collection_select с несколькими

У меня есть следующая проблема, использующая has_many: через отношение many-to-many в multi-select через collection_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

Модель поставщика:

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

Отношение Entity:

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

И это форма. Обратите внимание, что я не мог заставить его работать без указания имени: 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 %>

Если я удалю имя:, я получу это сообщение об ошибке:

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 содержат только один поставщик_ид вместо массива vend_ids:

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

Ответ 1

У меня проблема решена. В этом случае использование 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}) %>