当 ActiveRecord 模型上有另一个调用时,可以删除 .all 吗?
Is it ok to drop .all when there is another call on ActiveRecord model?
我正在调整在 Profile 模型上工作的代码,以增加 activate/deactivate Profile 的可能性。在某些地方有代码 Profile.all
,而新引入的代码将是 Profile.active.all
。在我看来,现在删除 .all
是可以的,但我不确定 .all
是否没有一些神奇之处。
我检查了docs for all and it mentions default scope. Somehow it seems to me AR should always use default scope unless I call unscoped。
肯定没那么多地方,后来改不了了。我只是好奇。
是的,删除它是安全的。
只是为了确保运行控制台中的这两个查询:
Profile.active.all.to_sql
Profile.active.to_sql
如果我没看错代码,大部分查询方法实际上都委托给了:all
。您可以避免 .all
因为 ActiveRecord 实际上会为您添加它们中的大多数。
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
我正在调整在 Profile 模型上工作的代码,以增加 activate/deactivate Profile 的可能性。在某些地方有代码 Profile.all
,而新引入的代码将是 Profile.active.all
。在我看来,现在删除 .all
是可以的,但我不确定 .all
是否没有一些神奇之处。
我检查了docs for all and it mentions default scope. Somehow it seems to me AR should always use default scope unless I call unscoped。
肯定没那么多地方,后来改不了了。我只是好奇。
是的,删除它是安全的。
只是为了确保运行控制台中的这两个查询:
Profile.active.all.to_sql
Profile.active.to_sql
如果我没看错代码,大部分查询方法实际上都委托给了:all
。您可以避免 .all
因为 ActiveRecord 实际上会为您添加它们中的大多数。
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