Rails Active Record Query for Double Nested Joins with a Select Call

混江龙づ霸主 提交于 2019-12-11 00:30:09

问题


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

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