Iterating over an association in_groups_of (i.e. "wrapper every X items")

14 views
Skip to first unread message

Timothy Spangler

unread,
Sep 15, 2015, 6:49:06 PM9/15/15
to SimpleForm
I have a HABTM association connecting Users to Languages. I am using simple_fields_for and accepts_nested_attributes_for to allow my UserInfo form to accept languages for the association.

My goal is to display a checkbox for each language, nicely aligned and following Bootstrap conventions. I've tried this:

<%= f.simple_fields_for :user do |fields| %>
  <%= fields.association :languages, as: :check_boxes, label_method: :english_and_native_name, label: 'Languages spoken', wrapper_html: {class: 'row'}, item_wrapper_tag: 'span', item_wrapper_class: 'col-md-4' %>
<% end %>

Of course, this only ever creates one row tag (the collection wrapper), and as such the boxes don't stack nicely and everything gets thrown off, especially the collection label ("Languages spoken").

What I need is to create a new row every 3 languages, which led me to something more along the lines of this:

<% Language.all.in_groups_of(3, false) do |languages| %>
  <div class="row">
    <% languages.each do |language| %>
      <div class="col-md-4">
        <span class="checkbox">
          <%= fields.label :language_ids, language.english_and_native_name do %>
            <%= fields.check_box :language_ids %>
            <%= language.english_and_native_name %>
          <% end %>
        </span>
      </div>
    <% end %>
  </div>    
<% end %>

This creates a perfectly aligned grid of checkboxes, but with the wrong names and values:

<div class="col-md-4">
  <span class="checkbox">
    <label for="user_info_user_attributes_language_ids">
      <input name="user_info[user_attributes][language_ids]" type="hidden" value="0"><input type="checkbox" value="1" name="user_info[user_attributes][language_ids]" id="user_info_user_attributes_language_ids">Japanese (日本語)
    </label>
  </span>
</div>

What is the most SimpleForm-appropriate way to do what I'm trying to do?
Reply all
Reply to author
Forward
0 new messages