2010-06-05 15 views

回答

0

我發現有效的東西。

在操作模式:

def self.owned_by (user) 
    joins("join tasks on actions.task_id = tasks.id"). 
    joins("join projects on tasks.list_id = projects.id"). 
    where("projects.user_id = ?" , user.id) 
end 

從控制檯:

u=User.find(1) 
Action.owned_by(u).count 

=> 521 # which is correct 

我MOT知道它的最好辦法做到這一點,因爲我是一個有點新的SQL。我感覺它可以變得更加簡潔。

編輯稍好

Action.joins(:task => [{:project => :user }]).where(:projects => {:user_id => user.id }) 
0

我不認爲範圍是必要的這個,如果你使用nested_has_many_through插件。

class User < ActiveRecord::Base 

    has_many :projects 
    has_many :tasks, :through => :projects 
    has_many :actions, :through => :tasks 

end 

class Project < ActiveRecord::Base 

    has_many :tasks 
    has_many :actions, :through => :tasks 

end 

User.first.actions 
+0

感謝。我嘗試過,但它不太工作。 有一個用戶有2個項目共80個任務,這些任務共有500個動作 當我詢問user.actions它返回的任務和user.actions.count是80 – 2010-06-26 11:26:01

+0

謝謝布萊恩 - 我會看看這個插件 – 2010-06-26 18:11:54