我的模型Parent
has_one
Child
。但是,出于某些逻辑原因,我需要将外键存储在Parent
而不是Child
中。
是否可以在has_one
表中定义Parent
与外键的关系?
我不想定义Parent
belongs_to
Child
,因为我想通过定义Parent
从accepts_nested_attributes_for
创建这些对象。
答案 0 :(得分:1)
这是has_one
的倒数 - 即belongs_to
。
有关详细信息,请参阅http://guides.rubyonrails.org/association_basics.html#choosing-between-belongs-to-and-has-one。
答案 1 :(得分:0)
如果你想要一些与accepts_nested_attributes_for
类似的东西,你可以写自己的吸气剂吗?
def child_attributes=(attrs)
child_id? ? (child = Child.create(attrs)) : child.update_attributes(attrs))
end
child = Child.create(attrs)
不save
Parent