首页 > 解决方案 > Rails 活动记录中的委托

问题描述

在深入研究 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 的类或模块。那么这些方法去哪儿了。

标签: ruby-on-railsactiverecord

解决方案


所有这些方法都是ActiveRecord::Relation. YourModel.all返回 a YourModel::ActiveRecord_Relation(尽管名称不同,但它是一个 ActiveRecord::Relation)。因此,该代表团使用一种速记方式,YourModel.all.find无需一直写作.all


推荐阅读