【问题标题】:rails: how do I build an active-relation scope to traverse many tables?rails:如何建立一个活动关系范围来遍历许多表?
【发布时间】:2010-06-05 03:09:08
【问题描述】:

我有这些表和关系:

user has_many projects
project has_many tasks
task has_many actions

我想构建一个范围,允许我选择所有当前用户的操作,无论他们属于哪个项目或任务。

谢谢

【问题讨论】:

    标签: activerecord ruby-on-rails-3 arel


    【解决方案1】:

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

    【讨论】:

    • 谢谢。我试过了,但效果不太好。有一个用户有 2 个项目,总共有 80 个任务,这些任务总共有 500 个操作当我要求 user.actions 它返回任务并且 user.actions.count 是 80
    • 谢谢 Bryan - 我会看看那个插件
    【解决方案2】:

    我发现了一些有用的东西。

    在动作模型中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-10
      • 2021-07-12
      • 2018-04-07
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多