HereToLearn
HereToLearn

Reputation: 107

How to join more than one table rails

I've got a bit of code that I'm looking at the moment :

User.includes([:profile => :schedule]).where('...')

This loads all profiles and their schedules. So the query produced by this is select * user fields, select * profile fields, select * schedule fields

I'm filtering out users based on one field from profile and based on one field from profiles schedule but this above statement is selecting all the fields from all of these.

So I tried to do it with joins :

User.joins(:profile).joins('profiles.schedule').where('....').select('....')

This is throwing out error. I'm a former Java developer, still learning the rails stuff.

Upvotes: 1

Views: 79

Answers (3)

Dheer
Dheer

Reputation: 793

Try this:

User.joins(profile: [:schedule]).where('...')

or

User.joins(profile: :schedule).where('...')

Upvotes: 0

ediblecode
ediblecode

Reputation: 11971

If you've set your Profile model to have the association Schedule using the has_many through association then you can just use this:

User.joins(:schedule).where('...')

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

This should work:

User.joins(profile: :schedule).where('....').select('....')

Upvotes: 1

Related Questions