开发者

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" } }

开发者_如何学JAVAHow 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

That'd be my educated guess... Where "(...)" would be your arguments for the new parent


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜