活动记录范围的可交换性和顺序

Commutability and order of active record scopes

"sorting" "filters"(Desc 或 Asc)在 Rails' Active Record 查询中的位置在性能和逻辑方面是否重要?

例如以下范围 1 与范围 2 相同

范围 1

scope :default_stream, -> { order(deal_end_date: :asc) } # this is the "sorting query"
scope :scope_1,
      lambda { default_stream.where('deal_start_date <= ? AND deal_end_date >= ?', Time.zone.now, Time.zone.now).where(is_cool: true) }

范围 2

scope :scope_2,
      lambda { Deal.all.where('deal_start_date <= ? AND deal_end_date >= ?', Time.zone.now, Time.zone.now).where(is_cool: true).order(deal_end_date: :asc) }

我应该先使用 "sorting query" 然后使用其他过滤器 (scope1) 还是相反 (scope2)?

不确定它是否有影响,但让我知道交易数量可能非常重要 (>100000)

没关系。直到您尝试读取结果的时间点,您的示波器才真正被评估。 orderwhere 子句可以按任何顺序附加到您的关系中,因为它们在最终 SQL 查询中放置在同一位置。

如有疑问,请尝试两种方法并在您的范围上调用 .to_sql。你会发现 scope1.to_sql 等同于 scope2.to_sql.

给定一个简单的 Post 模型,您会发现 Post.order(:name).where(active: true)Post.where(active: true).order(:name) 产品 相同 SQL:

select * from posts where active = true order by name

orderwhere 都没有发生 "first",那是不可能的。只生成了一个 SQL 查询,其所有不同的子句(where、order、limit、offset 等)都去了它们需要去的地方以产生语法上有效的查询。