English 中文(简体)
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

最佳回答

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 })
问题回答

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




相关问题
Codeigniter WHERE on "AS" field

I have a query where I need to modify the selected data and I want to limit my results of that data. For instance: SELECT table_id, radians( 25 ) AS rad FROM test_table WHERE rad < 5 ORDER BY rad ...

Problem find joined table in rails

I have model represent association rule (Body => Head) def Item has_many :heads has_many :bodies ... end def Rule has_many :heads has_many :bodies ... end def Body belongs_to :item belongs_to :rule ...

FreeTDS Bad token from the server (SQL Server)

Today we had a lot more activity than normal between our Ruby on Rails application and our remote legacy SQL Server 2005 database, and we started getting the error below intermittently. What is is? ...

Castle ActiveRecord: one-to-one

While playing around with one-to-one associations in castle activerecord I stumbled upon the following problem: I m trying to model a one-to-one relationship (user-userprofile in this case). I ...

Sending email updates: model or observer?

I have an Event model, which stores an event feed for each user. I also need to email the updates to users which have enabled email notifications in their profile. From an architectural point of view,...

activerecord has_many :through find with one sql call

I have a these 3 models: class User < ActiveRecord::Base has_many :permissions, :dependent => :destroy has_many :roles, :through => :permissions end class Permission < ActiveRecord::...

热门标签