Rails returning all of second level association

本秂侑毒 提交于 2019-12-23 04:43:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!