为什么这些named_scope会导致重复的INNER JOIN?

时间:2010-07-09 18:08:35

标签: ruby-on-rails authorization inner-join named-scope nested-sets

我有一个模型,我用它来使用awesome_nested_set插件跟踪层次结构组织中的权限。我遇到了一个问题,当两个named_scope链接在一起时,正在创建重复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

这两个named_scope位于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] }
}

这两个named_scope都需要加入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 个答案:

答案 0 :(得分:1)

尝试将for named范围中的join语句更改为:joins => {:memberships => :groups}。我怀疑has_many通过关系可能会导致它。