ruby-on-rails - 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 的类或模块。那么这些方法去哪儿了。
解决方案
所有这些方法都是ActiveRecord::Relation
. YourModel.all
返回 a YourModel::ActiveRecord_Relation
(尽管名称不同,但它是一个 ActiveRecord::Relation)。因此,该代表团使用一种速记方式,YourModel.all.find
无需一直写作.all
。
推荐阅读
- ms-word - 如何更改 ms word 中括号和括号(所有出现)的颜色
- angular - Angular Cucumber 找不到任何要执行的测试
- scala.js - 如何在 Scala.js 中将 Future 转换为 js.Promise?
- r - Packrat::restore() 用于系统依赖
- reactjs - useEffect trace origin for change
- powershell - 您可以在运行 Get-ChildItem 以编译文件夹大小列表时写入过滤器以排除某些文件夹吗?
- mysql - 如何在 MySQL 中进行自定义舍入?
- class - 如何在 kotlin 中明确指定正确的覆盖
- python - 替换python脚本中的字符串并执行脚本
- c# - 如何设置从 POST 返回到 /signin-oidc 的重定向位置?