somewhat new to Rails, so I'd appreciate any help you guys could offer.
Anyway, I have three models - Vote, Lunch, and Provider, and I'm looking to write a single Active Record call to pull:
The Vote model includes a lunch_id, the Lunch model includes a lunch_id (just called id) and the provider_id. The Provider model has a provider_id (just called an id.) In the Rails console, I can write:
v = Vote.joins(:lunch).select("lunches.date,votes.*").where(lunch_id: 1)
and that outputs all the data in the Vote model, plus the associated date from the Lunch model. Where I'm stuck is that I don't know how to "nest" this to then join to the Provider model.
I'm thinking this may have something to do with "has_many_through", but even after reading the documentation, I'm not sure how it would be implemented. Any thoughts here would be greatly appreciated!
Assuming all of your models have the correct has_many
and belongs_to
associations defined, you can join in multiple tables by passing in a hash to the join method instead of just a symbol.
Vote.joins(lunch: :provider).select('lunches.date, providers.name, votes.*').where(lunch_id: 1)
More information about these can be found in the 'Using Array/Hash of Named Associations' portion of the rails query inferface documentation.
http://guides.rubyonrails.org/active_record_querying.html#using-array-hash-of-named-associations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With