问题
I have the model Parent that has_one Child. However, for some logical reason, I need to store foreign key in Parent instead of Child.
Is it possible to define has_one relationship with foreign key in the Parent table?
I don't want to define Parent belongs_to Child, because I want to create these objects from Parent by defining accepts_nested_attributes_for.
回答1:
That is the inverse of has_one - that is belongs_to.
See http://guides.rubyonrails.org/association_basics.html#choosing-between-belongs-to-and-has-one for more information.
回答2:
If you want something that work similar to accepts_nested_attributes_for may be you could just write your own getter?
def child_attributes=(attrs)
child_id? ? (child = Child.create(attrs)) : child.update_attributes(attrs))
end
child = Child.create(attrs) doesn't save your Parent though
来源:https://stackoverflow.com/questions/18210286/has-many-with-foreign-key-stored-in-own-table