Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Active Record Join across 3 Tables

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:

  • All the data in the Vote table
  • The Lunch date in the Lunch table
  • The Provider name in the Provider table

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!

like image 289
sulleh Avatar asked Oct 22 '15 22:10

sulleh


1 Answers

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

like image 163
Alexa Y Avatar answered Nov 01 '22 13:11

Alexa Y