问题
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.
回答1:
Try:
User.joins(seat: :region).where(regions: { id: REGION_ID_HERE })
回答2:
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
回答3:
This should work without any join issues
User.joins(seat: :region).merge(Region.where(id: :id_here))
来源:https://stackoverflow.com/questions/29873065/rails-returning-all-of-second-level-association