Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for form_for when building an array from checkboxes

I'm making a form for an Order object, and the order has many Products, via a join table called OrderProducts. So, we've got something like this:

<% @order = Order.new %>
<% form_for @order do |f| %>
  <% @products.each do |product| %>
    ... want to iterate over products here to build up "order[product_ids][]", with one checkbox per product
  <% end %>
<% end %>

Usually for each product i would have a check_box_tag, saying

<%= check_box_tag "order[product_ids][]", product.id, @order.product_ids.include?(product.id) %>

But this, while working fine, always feels like a bit of a cop out. Is there a way i can do it with the f.check_box syntax? Important note - on the project in question I'm working in Rails 2.2.2, so a solution that works in rails 2 would be ideal.

like image 978
Max Williams Avatar asked Jan 13 '12 11:01

Max Williams


2 Answers

Rails <= 2.x (original)

<% @products.each do |product| -%>

  <% fields_for 'product[]' , product do |product_fields| -%>

    [...]
    <%= product_fields.check_box :id %>

  <% end -%>

<% end -%>

Rails >= 3.x (updated)

<% @products.each do |product| -%>

  <%= fields_for 'product[]' , product do |product_fields| -%>

    [...]
    <%= product_fields.check_box :id %>

  <% end -%>

<% end -%>
like image 105
Brad Werth Avatar answered Nov 16 '22 13:11

Brad Werth


I know the author was looking for version 2 answers, but this is the top hit for google and I though I would update:

One can do this ( I'm using 4.0, don't know how far back it goes ):

<%= form_for @order do |form| %>
  <%= form.collection_check_boxes(:product_ids, Product.all, :id, :labeling_method ) %>
<% end %>

For more info: http://edgeapi.rubyonrails.org...

like image 31
Carl Avatar answered Nov 16 '22 13:11

Carl