简体   繁体   中英

How do I submit and save a Child form with the Parent as nested fields?

Suppose you have the following Child class:

Child < AR
 belongs_to :parent
end

Which is associated to a Parent class:

Parent < AR
 has_many :children
end

I'd like to create a form within an action/view of the ChildrenController that allows the user to create a new Child and a new Parent if none has been assigned (I don't wan't a ParentsController since it doesn't have the same relevance to the application).

I've created a simple form in the new.haml.html view:

= simple_form @child do |c|
  c.input :field_for_child
  c.association :parent do |p|
    p.input :field_for_parent

The result is a params hash that looks like "child" => { "field_for_child" => "value1", "parent" => { "field_for_parent: => "value2" } }

How can I do to save "child" and "parent" in as fewer lines as possible?

@child.parent_id = (params[:parent][:field_for_parent]) || Parent.create(...).id

那是我的有根据的猜测...其中“(...)”是您对新父母的论点

in your model you write

class Child < AR
  belongs_to :parent
  accepts_nested_attributes_for :parent
end

and then inside your controller you can just save the child using the given attributes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM