has_many,外键存储在自己的表中

时间:2013-08-13 13:20:49

标签: ruby-on-rails activerecord

我的模型Parent has_one Child。但是,出于某些逻辑原因,我需要将外键存储在Parent而不是Child中。

是否可以在has_one表中定义Parent与外键的关系?

我不想定义Parent belongs_to Child,因为我想通过定义Parentaccepts_nested_attributes_for创建这些对象。

2 个答案:

答案 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