w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Active Record find record based on another object's inclusion in an association of first record

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 } }




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.