不幸的是,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
会失败。在加入关联后with_net_score
出现时, <{em> with_recent
和Story
都会失败。
您如何重写with_net_score
以便它添加到所选字段而不是重新排列它们,并且可以用with_recent
组合并加入?
答案 0 :(得分:0)
为此添加作者自己的解决方案:
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