[Form Helpers] Collection_select multiple and accepts_nested_attributes_for

Hello, I’m triying to set a form but I’m having problems.These are my
models:

class Post < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
accepts_nested_attributes_for :taggings, :limit => 3
end

class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :posts, :through => :taggings
end

class Tagging < ActiveRecord::Base
belongs_to :advert
belongs_to :tag
end

In my view posts/_form.html.erb:
<%= form_for @post do |f| %>
<%= f.fields_for :taggings do |t| %>
<% t.collection_select :tag_id, Tag.all, :id, :name, { :selected
=> @post.tag_ids }, { :multiple => true } %>
<% end %>
<% end %>

The problem is that I want a MULTIPLE select control for this
application but that seems incompatible with the
accepts_nested_attributes_for is expected. This control return an
array of options selected, like this:

  • One option selected ==>
    “post”=>{“taggings_attributes”=>{“0”=>{“tag_id”=>[“1”]}}}
  • Two options selected ==>
    “post”=>{“taggings_attributes”=>{“0”=>{“tag_id”=>[“1”,“2”]}}}

Instead, the accepts_nested_attributes_for is expected something like
this:

  • One option selected ==>
    “post”=>{“taggings_attributes”=>{“0”=>{“tag_id”=>“1”}}}
  • Two options selected ==>
    “post”=>{“taggings_attributes”=>{“0”=>{“tag_id”=>“1”},“1”=>{“tag_id”=>“2”}}}

I’m already clouded with this. One solution is to use a
collection_select control without multiple but I hope may have other
better solution.

Thanks very much. Daniel.

How about using ryanb’s nested_form gem? Should work well for your
case.

-cpr

Other solution is change the params hash for setup like
accepts_nested_attributes_for is expecting. I don’t know which is the
best solution for do it. In short, I want to create multiple nested
objects by selecting from a list.

Try this:

<%= collection_select(:taggings, :tag_ids, Tag.find(:all), :id, :name,
{}, {:multiple => true}) %>

Thanks cpr. It isn’t work for multiple select control but It’s okey
for a classic select.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs