0

I currently have three models that I am interested in: Region, Seat and User.

Region has many seats and seats have many available users.

I'd like to know what is the most efficient way in Rails to retrieve all of the available users for the seats which sit under a particular region.

Thanks in advance.

3 Answers3

4

Try:

User.joins(seat: :region).where(regions: { id: REGION_ID_HERE })
cschroed
  • 6,304
  • 6
  • 42
  • 56
  • This is broadly what I ended up doing, I realised the problem was that the User model sits in a different database connection for reasons. Thanks for all your help. – Bryce Roney Apr 26 '15 at 06:40
0

I think the nested join syntax by @cschroed might not work depending on how your data model is set up. If it doesn't you can try:

User.joins(:seat).joins('inner join regions ON regions.id = seats.region_id').where(regions: {id: REGION_ID_HERE})

In either case, only a single query is run. If you already have the Region, you could run region.users if you set up something like:

class Region < ActiveRecord::Base
  has_many :seats
  has_many :users, through: :seats
 end
Derek
  • 1,735
  • 17
  • 14
0

This should work without any join issues

User.joins(seat: :region).merge(Region.where(id: :id_here))
Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89