在ActiveRecord模型上还有另一个调用时,可以删除.all吗?

时间:2019-06-04 16:22:49

标签: ruby-on-rails activerecord rails-activerecord

我正在调整在Profile模型上工作的代码,以增加激活/停用Profile的可能性。在某些地方有代码Profile.all,新引入的代码是Profile.active.all。在我看来,现在放下.all是可以的,但是我不确定.all是否没有带来魔法。

我检查了docs for all,其中提到了默认范围。在我看来,除非我调用unscoped,否则AR应该始终使用默认范围。

绝对不是很多地方,所以以后不能更改。我很好奇。

2 个答案:

答案 0 :(得分:1)

是的,删除它很安全。

只需确保在控制台中运行这两个查询:

Profile.active.all.to_sql
Profile.active.to_sql

答案 1 :(得分:1)

如果我理解正确的代码,实际上大多数查询方法都被委派给:all。您可以避免使用.all,因为ActiveRecord实际上是为其中的大多数添加了它。

https://github.com/rails/rails/blob/b1879124a82b34168412ac699cf6f654e005c4d6/activerecord/lib/active_record/querying.rb

module ActiveRecord
  module Querying
    delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, to: :all
    delegate :second, :second!, :third, :third!, :fourth, :fourth!, :fifth, :fifth!, :forty_two, :forty_two!, to: :all
    delegate :first_or_create, :first_or_create!, :first_or_initialize, to: :all
    delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, to: :all
    delegate :find_by, :find_by!, to: :all
    delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, to: :all
    delegate :find_each, :find_in_batches, to: :all
    delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
             :where, :rewhere, :preload, :eager_load, :includes, :from, :lock, :readonly,
             :having, :create_with, :uniq, :distinct, :references, :none, :unscope, to: :all
    delegate :count, :average, :minimum, :maximum, :sum, :calculate, to: :all
    delegate :pluck, :ids, to: :all
相关问题