代码之家  ›  专栏  ›  技术社区  ›  Adam Lassek

为什么这些命名为“作用域”会导致重复的内部联接?

  •  0
  • Adam Lassek  · 技术社区  · 14 年前

    我有一个模型,用于跟踪分层组织中使用 awesome_nested_set 插件。我遇到了一个问题,两个 named_scope 当S链在一起时,会产生重复 INNER JOIN .

    class Group < ActiveRecord::Base
      acts_as_nested_set
      has_many :memberships
      has_many :accounts, :through => :memberships
      has_many :authorizations
      has_many :users, :through => :authorizations
    end
    

    两个 命名范围 S位于 Account 模型,用于按用户和组筛选帐户:

    named_scope :in_group, lambda { |id|
      group_ids = Group.find(id).self_and_descendants.collect(&:id)
      { :joins => :memberships, :conditions => ["memberships.group_id in (?)", group_ids] }
    }
    
    named_scope :for, lambda { |user|
      groups = user.authorizations.groups.collect(&:id) unless user.admin?
      user.admin ? {} : { :joins => :groups, :conditions => ["groups.id IN (?)", groups] }
    }
    

    这两个 命名范围 需要加入 memberships 但是他们不应该不需要重复就能做到吗?当它们被链接在一起时,mysql会出现以下错误:

    Mysql::Error: Not unique table/alias: 'memberships': SELECT `accounts`.* FROM `accounts` INNER JOIN `memberships` ON accounts.id = memberships.account_id INNER JOIN `memberships` ON `accounts`.`id` = `memberships`.`account_id` INNER JOIN `groups` ON `groups`.`id` = `memberships`.`group_id` WHERE ((memberships.group_id in (54,94)) AND (groups.id IN (54,94)))  ORDER BY business_name, location_name LIMIT 0, 75
    
    1 回复  |  直到 14 年前
        1
  •  1
  •   Geoff Lanotte    14 年前

    尝试将for命名范围中的join语句更改为 :joins => {:memberships => :groups} . 我怀疑这可能是因为他们之间的关系太多了。