问题
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