如何通过作用域关联访问集合?

时间:2012-10-01 17:27:36

标签: ruby-on-rails activerecord

class User < ActiveRecord::Base
    has_many :assignments
    has_many :projects, through: :assignments
end

class Project < ActiveRecord::Base
    has_many :assignments
    has_many :users, through: :assignments
end

class Assignment < ActiveRecord::Base
    belongs_to :user
    belongs_to :project
    scope :current_assignments, where(...)
end

我想获得当前分配给当前用户的所有项目。类似的东西:

current_user.current_assigned_projects

但是现在,我必须这样做:

current_user.assignments.current_assignments.map{ |a| a.project }.uniq

Project.includes(:users, :assignments).where('assignments.status' => 1, 'users.id' => current_user.id)

有没有什么好方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

这样的东西
class User < ActiveRecord::Base
   has_many :assignments
   has_many :projects, through: :assignments
   has_many :current_projects, conditions: 'assignments.status = 1', through: :assignments
end

应该有效。或者至少我希望如此;)