假设您有以下Child类:
Child < AR
belongs_to :parent
end它与Parent类相关联:
Parent < AR
has_many :children
end我想在ChildrenController的操作/视图中创建一个表单,允许用户创建一个新的Child和一个新的Parent (我不需要ParentsController,因为它与应用程序没有相同的相关性)。
我已经在new.haml.html视图中创建了一个简单的表单:
= simple_form @child do |c|
c.input :field_for_child
c.association :parent do |p|
p.input :field_for_parent结果是一个参数散列,看起来像"child" => { "field_for_child" => "value1", "parent" => { "field_for_parent: => "value2" } }
如何在尽可能少的行中保存"child“和"parent”?
发布于 2011-03-28 22:00:36
@child.parent_id = (params[:parent][:field_for_parent]) || Parent.create(...).id这是我有根据的猜测。其中"(...)“将会是你为新的父辈辩护
发布于 2011-03-28 22:01:10
在你的模型中,你写道
class Child < AR
belongs_to :parent
accepts_nested_attributes_for :parent
end然后在你的控制器中,你可以使用给定的属性来保存子对象。
https://stackoverflow.com/questions/5459979
复制相似问题