Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_many :through and collection_select with multiple

I have the following problem using a has_many :through many-to-many relation in a multi-select via collection_select :multiple => true. I have Suppliers who deliver many Ingredients which can be delivered by many Suppliers. Have a look:

The Ingredient model:

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

  has_many :suppliers, :through => :ingredient_suppliers
end

The Supplier model:

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

The relationship Entity:

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

And this is the form. Note that I could not get it to work without specifying the :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 %>

If I remove the :name, then I get this error message:

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

The problem now is, that the PUT parameters only contain one supplier_id instead of an array of supplier_ids:

"ingredient"=>{"name"=>"Rohstoff 3", "nr"=>"00300", "unit"=>"Stk.", "mol_per_unit"=>"0,00000", "description"=>"", "supplier_ids"=>"2"}
like image 273
agent smith Avatar asked Nov 23 '11 09:11

agent smith


1 Answers

I've got the problem solved. In this case, using fields_for was the error. The solution is using a collection_select, like this:

<%= collection_select(:ingredient, :supplier_ids, 
              Supplier.all(:order=>"name ASC"), 
              :id, :name, {:selected => @ingredient.supplier_ids, :include_blank => true}, {:multiple => true}) %>
like image 200
agent smith Avatar answered Nov 15 '22 17:11

agent smith