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.
T开发者_如何学Gohanks
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
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 })
精彩评论