【发布时间】:2010-06-05 03:09:08
【问题描述】:
我有这些表和关系:
user has_many projects
project has_many tasks
task has_many actions
我想构建一个范围,允许我选择所有当前用户的操作,无论他们属于哪个项目或任务。
谢谢
【问题讨论】:
标签: activerecord ruby-on-rails-3 arel
我有这些表和关系:
user has_many projects
project has_many tasks
task has_many actions
我想构建一个范围,允许我选择所有当前用户的操作,无论他们属于哪个项目或任务。
谢谢
【问题讨论】:
标签: activerecord ruby-on-rails-3 arel
如果您使用 nested_has_many_through 插件,我认为不需要作用域。
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
【讨论】:
我发现了一些有用的东西。
在动作模型中:
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
从控制台:
u=User.find(1)
Action.owned_by(u).count
=> 521 # which is correct
我不确定这是否是最好的方法,因为我对 sql 有点陌生。我觉得它可以更简洁。
编辑稍微好一点
Action.joins(:task => [{:project => :user }]).where(:projects => {:user_id => user.id })
【讨论】: