Rails:如何构建主动关系范围来遍历许多表?

发布于 2024-09-05 03:02:22 字数 167 浏览 5 评论 0原文

我有这些表和关系:

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.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

邮友 2024-09-12 03:02:22

如果您使用 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

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
記憶穿過時間隧道 2024-09-12 03:02:22

我找到了有用的东西。

在操作模型中:

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

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 })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文