2

What I have now gives me a dropdown menu where I can only select one:

<%= form_for(@submission) do |f| %>
    <%= f.collection_select :id, Submission::SUB_ID, :to_s, :to_s %>
<% end %>

where SUB_ID=[1,2,3] in model Submission

I want to implement a checkbox instead of a dropdown menu so that I can select multiple SUB_ID (i.e. 1&2 or 1&3 or 2&3 or 1&2&3). I tried to use this but it does not work:

<%= f.check_box :id, Submission::SUB_ID, :to_s, :to_s %>

Any idea?

1

4 Answers 4

1

Try this:

# view
<%= form_for(@submission) do |f| %>
  <%= Submission::SUB_ID.each do |sub_id| %>
    <%= f.checkbox 'ids[]', value: sub_id, checked: @submission.id == sub_id %>
    <%= sub_id %>
  <% end %>
<% end %>

# controller
params[:submission][:ids].each do |checked_sub_id|
  # do your logic here
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! this one is the closest, however, the sub_id style seems to be a little bit messy: all the ids are inline with a single checkbox
The style does not matter here: now that you know how to generate checkboxes for each sub_id, you can style it as your wishes. I just posted the least code possible to make it "universal"
1

you have to iterate over SUB_ID somehow like this...

<% Submission::SUB_ID.each do |ssid| %>
   <%= f.check_box "ids[]", value: ssid %>
<% end %>

or you can use formtastic gem. it has :as=>:check_boxes input fields http://www.ruby-doc.org/gems/docs/n/nuatt-formtastic-0.2.3/Formtastic/Inputs/CheckBoxesInput.html

Comments

0

The core answer is you need to loop over each item in Submission::SUB_ID and make a checkbox for each id. Depending on how your models are set up and what you want to do - you may need to be much more involved in the form building. I hesitate to provide specific examples without know more about how you want the data to come back to the controller

<%= form_for(@submission) do |f| %>
    <% Submission::SUB_ID.each do sub_id %>
      <%= f.check_box_tag 'submission_ids[]', sub_id %>
    <% end %>
<% end %>

Note that that will not default anything to checked and it does not come back as part of the submission parameters.

Usually when I have a similar situation I'm using nested forms to add or remove objects.

Comments

0

If you're using Rails 4, there is a new helper, collection_check_boxes, which helps streamline the building of your check boxes.

<%= f.collection_check_boxes :submission_ids, Submission::SUB_ID, :to_s, :to_s %>

Documentation:

If you look at the documentation in the second link, you'll also find how to use the optional block syntax to customise the HTML structure for each check box.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.