简体   繁体   中英

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 . And model B can belong to model C . I want an instance of A to refer to B 's C if B is present else refer to it's own C .

So I kind of want (for 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 . How do I achieve this?

Note: I also want my queries to be efficient for A , so A.all.includes(:C) should work.

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: ...).

The only one real issue you have after this is how to handle A.includes(:C). We can think about some way to write some custom solution to replace such behaviour. Anyway includes will execute additional query.

If you think such approach is useful for you, I will think about some custom solution and share my minds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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