代码之家  ›  专栏  ›  技术社区  ›  Mailo Světel

可以放弃吗?在activerecord模型上有另一个调用时全部放弃?

  •  0
  • Mailo Světel  · 技术社区  · 5 年前

    我正在调整在配置文件模型上工作的代码,以添加激活/停用配置文件的可能性。有些地方有密码 Profile.all 如果新引进的话 Profile.active.all . 在我看来,放下 .all 现在,但我不确定 所有 不会有魔法的。

    我检查过了 docs for all 它提到了默认范围。在我看来,除非我调用 unscoped .

    肯定没有那么多地方,所以我以后不能换了。我只是好奇。

    0 回复  |  直到 5 年前
        1
  •  1
  •   arieljuod    5 年前

    如果我正确理解代码,那么大多数查询方法实际上都被委托给 :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
    
        2
  •  1
  •   CAmador    5 年前

    是的,移除它是安全的。

    为了确保在控制台中运行这两个查询:

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