问题
I have the following schema:
Photos has many
Groups has many
Users.
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.
I problem is finding the least expensive query to resolve only the User.ids
affected.
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.
Given a photo, I am looking for the most efficient way to find a collection of the affected user id's.
Any help would be much appreciated!!!
回答1:
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 .
So, please try this.
回答2:
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.
来源:https://stackoverflow.com/questions/17691097/rails-active-record-query-for-double-nested-joins-with-a-select-call