Skip to content

Instantly share code, notes, and snippets.

@JoshReedSchramm
Created October 27, 2013 00:05
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JoshReedSchramm/7176154 to your computer and use it in GitHub Desktop.
Save JoshReedSchramm/7176154 to your computer and use it in GitHub Desktop.
An example of customizing collection_check_boxes in Rails 4. -- I'm working on converting a rails 3.2 app to Rails 4 and noticed that a couple of helpers from simple_form are now in the Rails core. I wanted to move away from dependencies as much as possible including getting rid of simple_form if possible so I went about converting the old view …
<%= f.collection_check_boxes :venue_ids, Venue.all, :id, :name, checked: Venue.all.map(&:id) do |b| %>
<span>
<%= b.check_box %>
<%= b.label %>
</span>
<% end %>
@nshki
Copy link

nshki commented Oct 15, 2014

Thanks for this. Was looking through the official documentation with no avail.

@tienshunlo
Copy link

(http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_check_boxes)
I can't understand why to use this code : "#{first_name.first}. #{last_name}"

And I tried this way, but it didn't work.
<%= builder.collection_check_boxes :questionnaire_surveys, :survey_id, Survey.all, :id, :name %>

I already posted my question here, could you please take a look and any suggestions will be greatly appreciated.
(http://stackoverflow.com/questions/31566905/not-sure-why-the-view-doest-work-rails-4-nested-attributes-and-has-many-throu)

@kroteDev
Copy link

Thanks . This helped me a lot. In my case i did a little modification
<%= f.collection_check_boxes :venue_ids, Venue.all, :id, :name, checked: JSON.parse(@method.venue_ids) %>
This way i was able to return the checked values

@vishal5963
Copy link

Hello,
Is there a way to add "Other" options with collection checkboxes? On selection of this "Other" checkbox, i need to enter a value from textbox and add it in my database.

@moyuanhuang
Copy link

@vishal5963

a little hacky way of achieving this:

    <% primary_options = my_options.collect do |option| %>
      <% [option,option] %>
    <% end %>

    <%= p.collection_check_boxes :my_options, primary_options, :first, :last do |option| %>
      <%= option.check_box + option.text %>
      <% if option.text == 'Other' %>
          <input type='text' id='other-input' class='other-textbox' value="option_group_other">
      <% end %>
    <% end %>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment