What I want to do is to get the equivalent of belongs_to through. My rationale is that I don't want to generate lots of db calls, while traversing my model structure.
My example in pseudo format:
Manufacturer
has_many: machines
Factory
has_many: machines
has_many: people
Machine
belongs_to: manufacturer
belongs_to: factory
People
belongs_to: factory
I want starting from a Manufacturer record(s), to get all the people in the factory where those manufacturers machines exist.
The only way I can think of is by iterating through manufacturer.machines.each, and calling factory.people (or calling people using a delegate), but I'd love to do it all in one call.
Is there a way?
In your Manufacturer
model you could have these relations:
has_many :machines # You probably already have this one
has_many :factories, through: :machines
has_many :people, through: :factories
Let's say bob
is a Manufacturer
. You can now get all the people in all the factories where bob
's machines exist.
bob.people
Note that I renamed the People
model to Person
when I tested it. You should try to keep your model names singular as much as possible.
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.