Rails 4 Form: has_many through: checkboxes

后端 未结 2 1555
自闭症患者
自闭症患者 2020-12-13 09:25

Original question

Two resources: users and animals. When creating a user, the client selects check boxes to say how many

相关标签:
2条回答
  • 2020-12-13 09:46
    <% Animal.all.each do |animal| %>
       <label>
          <%= check_box_tag "user[animal_ids][]", animal.id, f.object.animals.include?(animal) %>
          <%= animal.name %>
       </label>
    <% end %>
    

    and you have to accept a hash with an array of ids on your controller params, something like

    {  animal_ids: [] }
    

    maybe reading this can help: http://millarian.com/programming/ruby-on-rails/quick-tip-has_many-through-checkboxes/

    0 讨论(0)
  • 2020-12-13 09:55

    collection_check_boxes is a better option:

    <%= f.collection_check_boxes(:animal_ids, Animal.all, :id, :name) do |animal| %>
      <%= animal.label { animal.check_box } %>
    <% end %>
    
    0 讨论(0)
提交回复
热议问题