Rails 4 Form: has_many through: checkboxes

梦想与她 提交于 2019-11-28 18:12:28
<% 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/

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 %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!