[英]How do I get access to the .find() method in Ruby on Rails?
我知道如何使用find
方法,並且我想了解如何訪問它的邏輯。 我試圖弄清楚ActiveRecord
如何提供對find
方法的訪問。
據我所知,所有生成的模型都繼承自ActiveRecord::Base
。 根據源文件, find
方法似乎位於FinderMethods
模塊內部。 但是,我找不到ActiveRecord::Base
如何或以何種方式與FinderMethods
模塊綁定在一起以提供對find
方法的訪問。
如果有人可以幫助解釋,那將是感激的。
這里是:
$ grep include.FinderMethods . -r
./activerecord-4.2.8/lib/active_record/relation.rb: include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
如前所述,您會在Relation類中找到該方法的原因是:
# Assume class User < ActiveRecord::Base
u = User.where('1=1').find(1)
如果您看得更深:
puts User.where('1=1').class.name
=> "ActiveRecord::Relation"
並且由於Relation類包含FinderMethods模塊,因此find方法將作為Relation類的實例方法可用,因此您可以進行上述調用:
User.where('1=1').find(1)
現在,如果您想知道為什么可以這樣做:
User.find(1)
您必須在ActiceRecord :: Base類中查看此行
extend Querying
在看到ActiveRecord :: Querying模塊的地方,您會發現以下行:
delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :none?, :one?, to: :all
因此,這里發生的是ActiveRecord :: Base將具有類方法find,因為它的擴展Querying誰通過Relation類中定義的all方法委派了find方法。 這里的關鍵是了解代表的工作,這是這樣做的地方:
FinderMethods是ActiveRecord :: Relation而不是ActiveRecord :: Base的一部分。
ActiveRecord :: Relation是將在數據庫上運行的查詢,而ActiveRecord:Base是ActiveRecord :: Relation 中行的實例 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.