从复选框构建数组时 form_for 的语法 [英] Syntax for form_for when building an array from checkboxes
问题描述
我正在为 Order 对象创建一个表单,并且该订单通过名为 OrderProducts 的连接表包含许多产品.所以,我们有这样的事情:
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 %>
通常对于每个产品,我都会有一个 check_box_tag,说
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) %>
但这虽然工作正常,但总感觉有点像警察.有没有办法用 f.check_box
语法来做到这一点?重要说明 - 关于我在 Rails 2.2.2 中工作的相关项目,因此适用于 rails 2 的解决方案将是理想的.
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.
推荐答案
Rails <= 2.x(原创)
<% @products.each do |product| -%>
<% fields_for 'product[]' , product do |product_fields| -%>
[...]
<%= product_fields.check_box :id %>
<% end -%>
<% end -%>
Rails >= 3.x(更新)
<% @products.each do |product| -%>
<%= fields_for 'product[]' , product do |product_fields| -%>
[...]
<%= product_fields.check_box :id %>
<% end -%>
<% end -%>
这篇关于从复选框构建数组时 form_for 的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!