has_many with foreign key stored in own table

ぐ巨炮叔叔 提交于 2019-12-11 15:46:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!