Create has_many relationships from form

回眸只為那壹抹淺笑 提交于 2020-01-17 07:05:42

问题


So if I have a two models like this:

#parent.rb
class Parent < ApplicationRecord
    has_many :children
end

#children.rb
class Child < ApplicationRecord
    belongs_to :parent
end

How would you create a form that allows you to create multiple children in the form that creates the parent?


回答1:


Cocoon[0] solves this problem quite nicely, and has a great example app.

Rolling on the back-end, throw accepts_nested_attributes_for :children on your Parent model, do some fields_for (or simple_fields_for) stuff in your form, and make sure you can assign the attributes by adding children_attributes: [:name, :age] to your parent_params.

[0] https://github.com/nathanvda/cocoon



来源:https://stackoverflow.com/questions/42603139/create-has-many-relationships-from-form

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