【问题标题】:Find top scored from parent and all their children in Rails在 Rails 中查找父母及其所有孩子的最高分
【发布时间】:2014-01-29 17:50:53
【问题描述】:

我有一个名为 User 的模型,它具有如下自联接关联:

has_many :children, class_name: "User",
    foreign_key: "parent_id"
belongs_to :parent, class_name: "User"

它还与 Post 模型有关联:

User has_many post

每个 Post 对象都有一个 score 属性,我正在尝试为给定用户及其孩子找到得分最高、得分大于 0 且满足特定属性的帖子。所以现在,我的 Post 模型中有这个方法:

def self.top_related_scored_by_user_id(user_id, max)
    where(:user_id => user_id).
      where(:related_image => true).
      where('score > 0').
      order(score: :desc).
      first(max)
  end

但是,我希望不仅可以查找具有 user_id 的用户,还可以查找他们的孩子。我该怎么做?

谢谢

【问题讨论】:

    标签: sql ruby-on-rails model


    【解决方案1】:

    很简单:

    def self.top_related_scored_by_user_id(user_ids, max = nil)
      user_ids = user_ids.kind_of?(Array) ? user_ids : [user_ids]
      scope = where(:user_id => user_ids)
      scope = scope.where(:related_image => true)
      scope = scope.where('score > 0')
      scope = scope.order(score: :desc)
      scope = scope.limit(max) if max.present?
      scope
    end
    

    你可以给 where 子句提供一个 id 数组,它会生成这样的条件:

    WHERE id IN (1, 2, 3, 4)
    

    对您的方法进行一点改进,使其更加灵活:

    def self.top_related_scored_by_user_id(user_ids, options = {})
      options = { limit: 10, order: 'score DESC', 
                  score: 0, related_image: true  }.merge(options)
      user_ids = user_ids.kind_of?(Array) ? user_ids : [user_ids]
    
      scope = where(:user_id => user_ids)
      scope = scope.where(:related_image => options[:related_image])
      scope = scope.where('score > ?', options[:score])
      scope = scope.order(options[:order])
      scope = scope.limit(options[:limit])
      scope
    end
    

    这样您可以轻松设置具有相同功能的选项,并且它具有可以根据需要覆盖的默认值。

    【讨论】:

    • 哦,好的。所以在使用方法之前我需要弄清楚id(父母和孩子),对吧?
    • 是的,您需要在使用此方法之前检索这些 id。
    • 如果 id 数组可能很大,您可能需要使用子查询将工作卸载到数据库中。
    猜你喜欢
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多