Search code examples
ruby-on-railsruby-on-rails-4has-and-belongs-to-manyform-helpers

Refactor HABTM with checkbox


i wanna refactor this code:

  <%= hidden_field_tag "contact[group_ids][]", nil %>
  <% Group.all.each do |g| %>
      <%= check_box_tag "contact[group_ids][]", g.id, @contact.group_ids.include?(g.id)%>
      <%= label_tag g.name %><br>
  <% end %>

I want use the form methods for this, example, but using check_box:

<%= f.collection_select(:departament_ids, Departament.all, :id, :name, {include_blank: true}, {multiple: true}) %>

Or other way, but i guess very confuse use hidden_field_tag for edits in case of blank options and @contact.group_ids.include?(g.id) for options was choosed.

Any help? Sorry my bad english


Solution

  • As you're using rails 4 you can use collection_check_boxes

    It will work the same way as collection_select so

    <%= f.collection_check_boxes(:departament_ids, Departament.all, :id, :name) %>