views:

139

answers:

2

I have these tables and relationships:

user has_many projects
project has_many tasks
task has_many actions

I would like to build a scope that allows me to select all of the current users actions, regardless of what project or task they belong to.

Thanks

A: 

I don't think scopes are necessary for this if you use the nested_has_many_through plugin.

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
Bryan Ash
Thanks for this. I tried it but its not quite working.there is a user with 2 projects with a total of 80 tasks and those tasks collectively have 500 actionsWhen I ask for user.actions it returns the tasks and the user.actions.count is 80
Thanks Bryan - I'll have a look at that plugin
A: 

I found something that works.

In the Actions model:

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

From the console:

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

 => 521 # which is correct

I'm mot sure if its the best way to do it as I'm a bit new to sql. I get the feeling it could be made more concise.

EDIT Slightly better

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