【问题标题】:Querying through a self join reference in rails通过 rails 中的自连接引用进行查询
【发布时间】:2013-12-06 16:31:57
【问题描述】:

我有usersthings的模型

用户可以有一个leader 和多个followers,它们是其他用户。用户也可以有things

所以我有这些使用自连接关系的定义:

class User < ActiveRecord::Base
    has_many :things, dependent: :destroy
    has_many :followers, :class_name => 'User', :foreign_key => 'leader_id'
    belongs_to :leader, :class_name => 'User', :foreign_key => 'leader_id'
end

class Thing < ActiveRecord::Base
    belongs_to :user
end

所以我可以通过询问来查询things 的列表,例如User.first.things。我还可以通过User.first.followers 获得userfollowers 列表。

如何获取用户的关注者拥有的东西的列表。我想我可能需要使用has_many through 关系,但我似乎无法弄清楚,因为我不确定如何处理Leader 可以通过“追随者”拥有things 的事实,但是也直接自己

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 has-many-through


    【解决方案1】:

    怎么样:

    all_things = (your_user.followers.each { |f| f.things }).flatten
    

    这应该返回一个包含things 的数组,该数组属于your_user 的所有关注者。

    【讨论】:

      【解决方案2】:

      类似这样的:

      def all_things
        Thing.where(:user_id => followers.map(&:id).push(id))
      end
      

      它返回一个scope,所以你应该能够继续这个链,例如:

      User.first.all_things.visible
      

      更新

      如果您只对关注者的东西感兴趣而不将用户的东西添加到批处理中,那么最好直接使用has_many through

      has_many :followers_things, :through => :followers, :source => :things
      

      查看this other SO thread

      【讨论】:

      • 请注意,此解决方案并未遵循leadership 的所有级别之间的无限递归。这意味着该解决方案没有考虑到 follower 也可以是其他 usersleader,因此也继承了 things
      • 这是在正确的轨道上。目前它返回(顾名思义)user 拥有的所有东西以及他们的followers 拥有的所有东西。我只想要他们followers 拥有的东西。但我应该可以从这里算出来
      • 知道了,只需删除.push(id) 这样:`Thing.where(:user_id => followers.map(&:id))' 就可以满足我的需要
      • 我对您描述的部分感到困惑:领导者可以通过“追随者”拥有东西,但也可以直接拥有自己
      猜你喜欢
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2016-08-06
      相关资源
      最近更新 更多