简体   繁体   English

是否有ActiveRecord的条件belongs_to和has_one关联?

[英]Have conditional belongs_to and has_one associations for ActiveRecord?

Say I have a model A that can belong to model B and model C . 假设我有一个模型A ,它可以属于模型B和模型C And model B can belong to model C . 模型B可以属于模型C I want an instance of A to refer to B 's C if B is present else refer to it's own C . 我希望A的实例引用BC如果B存在),否则引用它自己的C

So I kind of want (for A ) 所以我有点想要(对于A

belongs_to :B, optional: true
belongs_to :C
has_one    :C, through: :B

but I want the association of C to be dependent on the presence of B . 但我希望C的关联取决于B的存在。 How do I achieve this? 我该如何实现?

Note: I also want my queries to be efficient for A , so A.all.includes(:C) should work. 注意:我也希望查询对A有效,因此A.all.includes(:C)应该可以工作。

I would go with polymorphic association, so model A has either B (association_type: 'B' and association_id: ...) or C (association_type: 'C' and association_id: ...). 我将使用多态关联,因此模型A具有B (association_type:“ B”和association_id:...)或C (association_type:“ C”和association_id:...)。

The only one real issue you have after this is how to handle A.includes(:C). 在此之后,您唯一真正遇到的问题是如何处理A.includes(:C)。 We can think about some way to write some custom solution to replace such behaviour. 我们可以考虑一种写一些自定义解决方案来替代这种行为的方法。 Anyway includes will execute additional query. 无论如何, includes将执行附加查询。

If you think such approach is useful for you, I will think about some custom solution and share my minds. 如果您认为这种方法对您有用,那么我将考虑一些自定义解决方案并分享我的想法。

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

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