Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

ruby on rails - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 -%>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...