[英]Rails Active Record Query for Double Nested Joins with a Select Call
I have the following schema: 我有以下架构:
Photos has many
Groups has many
Users. 照片
has many
组has many
用户。
I am using this Rails server as a backend to an iOS application and constantly need to push out notifications to all involved users of a group when a photo is added. 我将这个Rails服务器用作iOS应用程序的后端,并且在添加照片时不断需要向组中所有涉及的用户推送通知。
I problem is finding the least expensive query to resolve only the User.ids
affected. 我的问题是找到最便宜的查询来仅解决受影响的
User.ids
So far I have 到目前为止,我有
Photo.find(1).groups.joins(:users)
I know that I have to put a select argument after this, but can't figure out the syntax for the life of me. 我知道我必须在此之后添加一个select参数,但是无法弄清楚我一生的语法。
Given a photo, I am looking for the most efficient way to find a collection of the affected user id's. 给定一张照片,我正在寻找最有效的方法来查找受影响的用户ID的集合。
Any help would be much appreciated!!! 任何帮助将非常感激!!!
In your Photo model, you can have another associations called users 在您的照片模型中,您可以具有另一个称为用户的关联
has_many :group_users, :through => :groups, :source => :users
Then you can find the users by the following code 然后您可以通过以下代码找到用户
@photo = Photo.includes([:group_users]).where("photos.id = ?", 1).first
@affected_users = []
@photo.group_users.map {|user| @affected_users << user.id}
Now the @affected_users
contains all the user ids. 现在,
@affected_users
包含所有用户ID。
users_id = []
Group.where(photo_id: 1).users.collect{|u| users_id << u.id}
puts users_id
As Photo has_many
groups, so, groups belongs_to
photo and groups table has photo_id
as foreign key . 由于Photo具有
has_many
群组,因此, photo_id
belongs_to
群组,而groups表具有photo_id
作为外键。
So, please try this. 因此,请尝试此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.