开发者

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. Thus I can access Model2 from Model1 as well as Model1 from Model2. Now my question is, can I change the relationship to Model2 belongs_to Model1 and Model1 has_one Model2? It also can let me traverse from Model1 to Model2 and from Model2 to Model1. I'm not sure of that, anyone can explain it please开发者_StackOverflow?

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜