简体   繁体   English

两个模型可以互相归属吗?

[英]Can two models belong_to each other?

I have two models which are one-to-one to each other. 我有两个彼此一对一的模型。 A currently has one B. A当前有一个B。

Lately I encounter many cases where it is desirable if A keeps the id of B in order to simplify logic and boost performance. 最近,我遇到许多情况,为了简化逻辑并提高性能,A希望保留B的ID。 However I wonder if: 但是我想知道是否:

  1. this is possible 这个有可能
  2. would breach and convention 会违反惯例
  3. any thoughts really 真的有什么想法

UPDATE 更新

I was wrong, the left outer join would not be benefited by the extra foreign key. 我错了,额外的外键不能使左外部联接受益。

The only place I can think of is to find all A's which does not have B, an inner join is required on each of my 100000+ records. 我能想到的唯一地方是找到所有没有B的A,在我的100000+条记录中的每条都需要一个内部联接。 But if there is an id then I can know straight away which A has a B. 但是,如果有一个ID,那么我马上就能知道哪个A有一个B。

I don't believe this is possible - you have to decide where to keep the foreign key. 我认为这是不可能的-您必须决定在哪里保留外键。 Would it make sense for you to use a joining through relationship and for both your existing models to be has_one through the join? 对您而言,使用通过关联关系进行连接,并且将现有的两个模型都通过连接进行为has_one有意义吗?

Another alternative is to put A id on B, ie denormalize. 另一种选择是将A id放在B上,即反规范化。 This would allow you to figure out which A's without a B, and A's with a B. This might be appropriate for reporting scenarios when B's don't move between A's often. 这将使您找出哪个A不带B,一个A不带B。这可能适用于报告B不经常在A之间移动的情况。

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

相关问题 可以模拟“belongs_to”两个其他模型并具有嵌套关系? - can model “belong_to” two other models and have a nested relationship? Rails 4:子模型可以属于两个不同的父模型吗? - Rails 4: can a child model belong_to two different parent models 红宝石—两个模型可以互相归属吗? - ruby on rails — can two Models belong to each other? 用一个提交保存两个模型(属于第三个模型)? - Save two models (which belong_to a third model) with one submit? 具有多个belong_to 和命名的模型 - Models with multiple belong_to and naming 一个模型可以属于其他两个模型之一吗 - Can a model belong to either one of two other models 我怎样才能使用户具有has_many个对象,但每个对象都可以属于许多用户? - How can I make a user has_many objects but each object can belong_to MANY users? belong_to Post 和 belong_to User 的评论 - Comments that belong_to Post and belong_to User 在Ruby on Rails中,模型“ has_many”和“ belong_to”如何使用除主ID之外的其他字段? - In Ruby on Rails, how can a model “has_many” and “belong_to” using a different field other than primary ID? 两个belong_to引用同一张表+渴望加载 - Two belong_to referring the same table + eager loading
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM