在深入研究Rails源代码时,activerecord/lib/active_record/querying.rb
中有一些代码
QUERYING_METHODS = [
:find, :find_by, :find_by!, :take, :take!, :first, :first!, :last, :last!,
:second, :second!, :third, :third!, :fourth, :fourth!, :fifth, :fifth!,
:forty_two, :forty_two!, :third_to_last, :third_to_last!, :second_to_last, :second_to_last!,
:exists?, :any?, :many?, :none?, :one?,
:first_or_create, :first_or_create!, :first_or_initialize,
:find_or_create_by, :find_or_create_by!, :find_or_initialize_by,
:create_or_find_by, :create_or_find_by!,
:destroy_all, :delete_all, :update_all, :touch_all, :destroy_by, :delete_by,
:find_each, :find_in_batches, :in_batches,
:select, :reselect, :order, :reorder, :group, :limit, :offset, :joins, :left_joins, :left_outer_joins,
:where, :rewhere, :preload, :extract_associated, :eager_load, :includes, :from, :lock, :readonly, :extending, :or,
:having, :create_with, :distinct, :references, :none, :unscope, :optimizer_hints, :merge, :except, :only,
:count, :average, :minimum, :maximum, :sum, :calculate, :annotate,
:pluck, :pick, :ids
].freeze # :nodoc:
delegate(*QUERYING_METHODS, to: :all)
我无法理解to: :all
的含义,因为找不到任何名为all的类或模块。那么这些方法在哪里呢?
答案 0 :(得分:3)
所有这些方法都是ActiveRecord::Relation
的一部分。 YourModel.all
返回一个YourModel::ActiveRecord_Relation
(尽管名称不同,它还是一个ActiveRecord :: Relation)。因此,该代表团可以简化操作YourModel.all.find
,而不必一直写.all
。