0

我正在尝试创建一个命名范围,User.not_in_project(project)但我找不到正确的方法。

我将用户、项目和职责作为连接模型:

class User < ActiveRecord::Base
  has_many :duties, :extend => FindByAssociatedExtension
  has_many :projects, :through => :duties
end

class Duty < ActiveRecord::Base
  belongs_to :user
  belongs_to :project
end

class Project < ActiveRecord::Base
  has_many :duties
  has_many :users, :through => :duties
end

我尝试了named_scope与此 find 子句类似的方法:

User.all(:joins => :duties, :conditions => ['duties.project_id != ?', my_project])

但这不会让我返回没有的用户,my_project而是拥有除my_project.

换句话说,我希望命名范围的行为与此方法完全相同:

def self.not_present_in p
  self.all.reject{|u| u.projects.include?(p)}
end

我怎样才能做到这一点?

4

1 回答 1

1

在 SQL 中思考,查询应该是这样的:

select id
  from users
 where id not in (select id
                    from users join duties on users.id = duties.user_id
                    join projects on duties.project_id = projects.id
                   where projects.id = %)

但我不太确定使用named_scope 将如何工作。我会说使用类似的东西

def self.not_present_in p
  find_by_sql ["select id from users where id not in (select id from users join duties on users.id = duties.user_id join projects on duties.project_id = projects.id where projects.id = ?)", p]
end

不如使用 AR 漂亮,但会起作用(可能会为您节省一些查询)。

于 2009-09-07T19:19:25.407 回答