Syntax for form_for when building an array from checkboxes

后端 未结 4 969
北海茫月
北海茫月 2020-12-13 04:44

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:

<% @o         


        
相关标签:
4条回答
  • 2020-12-13 05:00

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

    0 讨论(0)
  • 2020-12-13 05:03

    I've done a number of multi checkbox forms over the years and different Rails version. Rails has never provided any really clean way to do it, but the "cop out" solution you came up with is pretty good isn't it? It's one line, it's explicit, and as long as the list of products is reasonably short it will perform adequately.

    To answer your specific question, f.check_box will never work for this. It's just short hand for the check_box_tag, but none of the semantics apply. If you want to go Rails native, the only possibility I think is to use nested attributes. Part of the problem is that there is not one obvious way for this type of thing to work. Rails core went through a lot of planning and feedback to come up with nested attributes as they exist, and though they seem a bit obtuse, they capture the most common use cases quite elegantly. But nested attributes were introduced in Rails 2.3, and besides they will introduce quite a bit of conceptual overhead for something which sounds like it doesn't need the complexity.

    There are also some plugins that provide helpers for this, although I haven't used any in a long time (since Rails 2 era actually). My impression is that they too are overkill unless you have many forms that make use of this pattern.

    In short, I think you should go ahead with your existing solution.

    0 讨论(0)
  • 2020-12-13 05:13

    formastic gem

    check_boxes option is very good to implement multiple checkboxes

    like

    f.input :yourcolumn, :as => :check_boxes, :collection => your_collection
    
    0 讨论(0)
  • 2020-12-13 05:21

    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 -%>
    
    0 讨论(0)
提交回复
热议问题