开发者

rails: how do I build an active-relation scope to traverse many tables?

开发者 https://www.devze.com 2023-01-02 14:40 出处:网络
I have these tables and relationships: user has_many projects project has_many tasks task has_many actions

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 })
0

精彩评论

暂无评论...
验证码 换一张
取 消