【问题标题】:Rails: How to conditionally apply ActiveRecord sorting by one attribute based on through association or other propertyRails:如何根据关联或其他属性有条件地按一个属性应用 ActiveRecord 排序
【发布时间】:2016-01-28 05:14:18
【问题描述】:

我正在 Rails 4 中构建一个基于标签的论坛,主题可以与标签相关联。

class Topic < ActiveRecord::Base
  ...
  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings
  ...
  scope :sort_by_latest_message, -> { order(latest_message_at: :desc) }
  scope :sort_by_sticky, -> { order(sticky: :desc) }
  ...
  scope :without_tags, -> { where.not(id: Tagging.select(:topic_id).uniq) }
  scope :with_tags, -> { joins(:tags).where("tag_id IS NOT NULL").uniq }
  ...
end

主题还有一个名为“sticky”的布尔列。

问题:我希望能够以将具有粘性属性的主题置于列表顶部的方式对主题进行排序,但前提是该主题与 at 有关联指定标签列表中的至少一个。然后主题将按 latest_message_at 属性排序。

这一切都发生在过滤过程之后。

例如,主题列表将包含带有标签 X、Y 和 Z 的主题,但只有带有标签 X 的粘性主题才真正被认为是粘性的,因此任何具有粘性属性但与标签 Y 相关联的主题或 Z 而不是标签 X 应该正常排序(按最新消息)。所以最终,列表将在顶部的标签 X 下具有粘性主题(按最新消息排序),然后是标签 X 下的所有其他主题加上标签 Y 和 Z 下的主题,无论它们是否具有粘性,按 latest_message_at 属性排序。

我目前有这样的设置:

def self.combine_sort_with_sticky(tag_ids, primary_sort)
  if tag_ids.empty?
    relevent_sticky_topics = without_tags.where(sticky: true)
    other_topics = union_scope(*[with_tags, without_tags.where(sticky: false)]) # union_scope is a method that creates an SQL union based on the scopes within
  else
    relevent_sticky_topics = joins(:tags).where("tag_id IN (?)", tag_ids).uniq.where(sticky: true)
    other_topics = joins(:tags).where("tag_id NOT IN (?) OR sticky = ?", tag_ids, false).uniq
  end
  combined_topics = relevent_sticky_topics.send(primary_sort) + other_topics.send(primary_sort) # Order is important, otherwise stickies will be at the bottom.
  combined_topics.uniq
end

所以当我调用 combine_sort_with_sticky([1], :sort_by_latest_message) 时,只有标签为 ID 1 和 sticky 属性的粘性主题被移动到列表的前面。我还要注意,当不过滤任何标签时,只有没有标签的主题才应该被认为是粘性的。

这似乎给出了我想要的结果,但是两个排序查询之间的 + 运算符让我担心,因为它将 ActiveRecord 关联转换为 Array 对象。

我正在寻找一种在有条件地应用两个排序范围中的第一个的同时维护 ActiveRecord 关联(例如范围或可能的另一个类模型)的方法。 Topic.all.sort_by_sticky.sort_by_latest_message 与我想要的很接近,但问题是它不加选择地按粘性属性排序,而不是仅将具有某些标签的粘性主题视为真正的粘性。

我一直在玩类似以下的范围:

scope :sort_by_relevant_sticky, ->(tag_ids) { joins(:tags).order("CASE WHEN tag_id IN (?) THEN sticky ELSE latest_message_at END DESC", tag_ids).uniq }

但这似乎不起作用。我对条件 SQL 不是很熟悉。

我的生产数据库是 Postgresql。

【问题讨论】:

    标签: ruby-on-rails postgresql sorting ruby-on-rails-4 activerecord


    【解决方案1】:

    这不是您问题的实际解决方案,但我会看看这个:https://github.com/mbleigh/acts-as-taggable-on :)

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多