【发布时间】:2009-09-07 11:43:21
【问题描述】:
我正在尝试创建像 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
我尝试使用类似于此 find 子句的named_scope:
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
我该怎么做?
【问题讨论】:
-
您想要返回什么?这个我不是很清楚。
-
我想要一个行为与此方法完全相同的命名范围:def self.not_present_in p self.all.reject{|u| u.projects.include?(p)} end 我希望它返回没有将 Project 作为参数传递的用户。这有帮助吗?
-
我编辑了问题以包含上述说明,因为它包含源代码。
标签: ruby-on-rails named-scope has-many