简体   繁体   中英

Active Record find record based on another object's inclusion in an association of first record

I have Users, Venues, and VenueManagers.

Given a user (current_user), I need to return the venue where this user is a venue_manager.

What's tricky is a venue can have multiple venue managers, and I'm running into the problem where the returned venues will only contain the one venue manager that's the current_user, and not contain the others.

Specifically, this is for a scope.

class Venue < ActiveRecord::Base

  has_and_belongs_to_many :venue_managers

  scope :for_venue_manager, -> (user) { includes(:venue_managers).where('venues_venue_managers.user_id = ?', user) }

end

That scope does not return all the venue managers unfortunately. Any input is kindly appreciated.

In order for a join to actually filter, it needs to be a joins and not an includes . So, first of all, you'll need to do

  scope :for_venue_manager, -> (user) { 
        joins(:venue_managers).where('venues_venue_managers.user_id = ?', user) }

This will give you the venues where this user is one of the managers. To have only the ones that have only this user as the manager, you can then filter by those who only have 1 manager:

  scope :for_venue_manager, -> (user) { 
        joins(:venue_managers).where('venues_venue_managers.user_id = ?', user).
        group(:venue_id).having('count(user_id) =  1') }

Or, in rails

  scope :for_venue_manager, -> (user) { 
        joins(:venue_managers).where('venues_venue_managers.user_id = ?', user).
        filter {|v| v.venue_managers.length == 1 } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM