简体   繁体   English

Active Record查找记录基于另一个对象在第一个记录的关联中的包含

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

I have Users, Venues, and VenueManagers. 我有用户,场地和VenueManager。

Given a user (current_user), I need to return the venue where this user is a venue_manager. 给定一个用户(current_user),我需要返回该用户是一个场所管理员的场所。

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. 棘手的是,一个场所可以有多个场所管理员,而我遇到的问题是,返回的场所将仅包含一个场所管理员(即current_user),而不包含其他场所管理员。

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 . 为了使joins实际过滤,它必须是joins而不是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: 要只让只有该用户作为管理员的用户,则可以按只有1个管理员的用户进行过滤:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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