【问题标题】:Composing ActiveRecord scopes with selects使用选择组合 ActiveRecord 范围
【发布时间】:2018-04-25 15:42:28
【问题描述】:

不幸的是,ActiveRecord 的 select 替换了现有的 SELECT 子句而不是添加到它,所以我无法编写查询。有人有解决方法吗?

示例模型:

class Story
  scope :recent, -> { where("created_at >= ?", 1.month.ago) }

  # deliberately simple examples, please don't get distracted memoizing, etc.
  scope :with_net_score, -> { select("`stories`.*, (upvotes - downvotes) as net_score" }
  scope :with_recent, -> { select("`stories.*, greatest(updated_at, last_vote_at) as recent") }
end

所以虽然我可以编写 Story.recent.with_net_score,但 Story.with_net_score.with_recent 却失败了。 两者Story 在加入关联后出现时,with_net_scorewith_recent 都会失败。

您将如何重写 with_net_score 以便它添加到选定的字段而不是复制它们并且可以与 with_recent 组合并加入?

【问题讨论】:

    标签: activerecord arel


    【解决方案1】:

    为此添加作者自己的解决方案:

    class ApplicationRecord < ActiveRecord::Base
      scope :select_fix, -> { select(self.arel_table.project(Arel.star)) }
    end
    

    https://github.com/lobsters/lobsters/blob/master/app/models/application_record.rb

    【讨论】:

      猜你喜欢
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      相关资源
      最近更新 更多