parm530
4/3/2018 - 5:36 PM

Collection Checkbox

Rails form helper for using collection checkboxes

In order to generate the object_ids, you need to ensure that the has_many relationship

exists in their respective models first!!!

<%= form_for(@movie, :url => {:action => "create"}) do |f| %>
<table id="movie-new">
<!--...-->
        <td><%= f.label(:genre, "Genre(s)") %></td>
        <td><%= f.collection_check_boxes(:genre_ids, Genre.all, :id, :name) %>
        <!--pay attention to the first arg: genre_ids, not just genre_id-->
        </td>
    </tr>
<!--...-->
<% end %>
  • movie has_many genres and genres has_many movies
<%= check_box_tag "is_out_of_stock_ids[]", object.id, nil, { id: "is_out_of_stock_#{object.id}" } %>