user3251174
user3251174

Reputation: 35

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

Upvotes: 0

Views: 54

Answers (1)

j-dexx
j-dexx

Reputation: 10416

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) %>

Upvotes: 1

Related Questions