简体   繁体   English

在Rails模型中,我可以将belongs_to更改为has_one并将has_one更改为belongs_to吗?

[英]In Rails models, can I change belongs_to to has_one and has_one to belongs_to?

If I have two models. 如果我有两个模型。 Model1 belongs_to Model2, and Model2 has_one Model1. Model1属于Model2,而Model2具有一个Model1。 Thus I can access Model2 from Model1 as well as Model1 from Model2. 因此,我可以从Model1访问Model2,也可以从Model2访问Model1。 Now my question is, can I change the relationship to Model2 belongs_to Model1 and Model1 has_one Model2 ? 现在我的问题是,我可以将与Model2的关系更改为Model1和Model1 has_one Model2的关系吗? It also can let me traverse from Model1 to Model2 and from Model2 to Model1. 它也可以让我从Model1遍历到Model2,从Model2遍历到Model1。 I'm not sure of that, anyone can explain it please? 我不确定,任何人都可以解释一下吗?

Thanks. 谢谢。

You can certainly change a relationship from one way round to the other. 您当然可以将一种关系从一种方式改变为另一种方式。

You'll obviously need to add a model_1_id column on the model_two table, migrate any existing associations across and remove the model_2_id column on the model_one table. 显然需要增加一个model_1_id在列model_two表,整个迁移任何现有的协会和删除model_2_id在列model_one表。

I can't think of anything else you'd particularly need to do to get it to work. 为了使它正常工作,我想不出您需要做的其他任何事情。 The associations behave pretty much identically when belongs_to is paired with has_one . belongs_tohas_one配对时,关联的行为几乎相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM