Search code examples
ruby-on-railssimple-formmodel-associations

Correct usage of simple_form collection_check_boxes


I have set up 2 models as following :

class Sector < ActiveRecord::Base
  attr_accessible :summary, :title, :sector_ids

  belongs_to :platform
end

and

class Platform < ActiveRecord::Base
attr_accessible :name, :url
    has_many :sectors
end

and a form which tries to use example from here as follows :

<%= simple_form_for @platform, :html => { :class => 'form-vertical'} do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <div class="row-fluid">
        <div class="span12">
            <div class="span6">
              <%=  field_set_tag "General" do %>
    <%= f.input :name %>
    <%= f.input :url %>
<%= f.collection_check_boxes :sector_ids, Sector.all, :title, :title %>

    <% end %>
</div>
</div>
</div>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

nevertheless, after I try to submit the form I get the following error :

Can't mass-assign protected attributes: sector_ids

What am I missing here? I successfully migrated the database after adding appropriate associations, but it seems like Rails doesnt really know what to do now wit the sector ids that are selected.

Solution :

class Sector < ActiveRecord::Base
  attr_accessible :summary, :title

  belongs_to :platforms
end

and

class Platform < ActiveRecord::Base
attr_accessible :name, :url, :platform_attributes, :sector_ids
    has_many :sectors
end

and in the view :

<%= f.association :sectors, :as => :check_boxes %>

Ofcourse, do not forget to run "rake db"migrate", in case you havent done it yet. I was also required to restart the server in order for the changes to apply.

I hope this helps someone.


Solution

  • First I think you should remove :sectors_ids from the attr_accessible of Sector and try.

    If the above doesn't works (which probably may not work), see the documentation of simple_form, specially read https://github.com/plataformatec/simple_form#associations and https://github.com/plataformatec/simple_form#collection-check-boxes; the last one makes what you are trying to do, but, in the associations they use has_and_belongs_to_many associations.

    Finally, check this out https://github.com/plataformatec/simple_form/issues/341

    Update The solution is to make a has_and_belongs_to_many relationship, there is no way out, because, you want to associate some sectors to one platform, but, you want to associate the same sectors to other platforms, otherwise you won't need checkbox, only nested forms to keep adding new records. You have to make this change in your database design and structure.