Nested Simple Form in Rails4 - has many through, save multiple records

巧了我就是萌 提交于 2019-12-03 08:48:05

Turns out that with simple_form this is actually rather simple (who knew?). It handles the magic of all the intermediary tables (together with Rails's awesomeness). All you need to do is this:

= simple_form_for(@human, html: { Pmultipart: true }), do |f|
  = f.association :orcs

I don't really use HAML so I'm not sure about that comma before do |f|. Here is what I'm trying to say in ERB HTML

<%= simple_form_for(@human) do |f| %>
  <%= f.association :orcs %>
<% end %>

Then in your controller's param sanitizer:

def orc_params
  params.require(:orc).permit(orc_ids: [])
end

And finally in your model:

class Human < ActiveRecord::Base
  ...
  accepts_nested_attributes_for :orcs
end

And that's it! It will automatically create the join objects. Don't you just love magic?

This will generate a multi-select field populated by all orcs. You can easily change this to checkboxes by using f.association :orcs, as: :check_boxes.

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