Search code examples
activerecordruby-on-rails-3arel

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


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


Solution

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