[英]Rails5 How can I build a feed with ActiveRecord Relation objects
[英]From the Rails API docs, how can I know that ActiveRecord::Relation supports “collect()”?
這是一個文檔導航問題。
我正在查看ActiveRecord::Relation
API doc 。
我從經驗中知道, Relation
支持each
和collect
。 大概它支持Enumerable
, 但是我不能從我的文檔中弄清楚 。
我想念什么嗎? 在Relation
的文檔中,沒有任何地方說它包含Enumerable
,並且它的mixin也沒有包含它。
collect()
如何到達那里的,為什么我在文檔中看不到它?
我從經驗中知道Relation支持每個人並收集
不,不是。
當您在其上調用Array方法時,它會使用to_a
生成其自身的to_a
數組,並且該數組接收.each
或.collect
。
請參閱委派 ,處理此問題的模塊。 具體來說,在method_missing
內部,它調用to_a
並將其代理到該方法,並返回結果。
def method_missing(method, *args, &block)
if @klass.respond_to?(method)
scoping { @klass.public_send(method, *args, &block) }
elsif array_delegable?(method)
to_a.public_send(method, *args, &block) # <-------- Here
elsif arel.respond_to?(method)
arel.public_send(method, *args, &block)
else
super
end
end
ActiveRecord::Relation
包括ActiveRecord::Delegation
,它負責將各種方法委托給其他對象。 就我們而言,重要的代表團是collect
to to_a
的代表團 。 此定義有效地意味着,調用relation.collect
等效於調用relation.to_a.collect
。
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, to: :to_a
請參閱Module#delegate
的文檔以詳細了解此委派的工作方式。
現在, 如我們所知 , Relation#to_a
返回一個包含關系數據的簡單數組。 因此,調用的collect
方法實際上是數組之一。
這確實有點隱藏,並且涉及大量的元編程和線程安全性問題,因此很難記錄。 但是,出於最相關的目的,關系的行為類似於后期綁定數組,應以這種方式對待。
畢竟,您正在使用Ruby。 使用Method#owner
方法可以很容易地回答此類信息:
2.1.2 :004 > Comment.where(value_new: "")
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."value_new" = ''
=> #<ActiveRecord::Relation []>
2.1.2 :005 > Comment.where(value_new: "").method(:collect)
=> #<Method: Comment::ActiveRecord_Relation(ActiveRecord::Delegation)#collect>
2.1.2 :006 > Comment.where(value_new: "").method(:collect).owner
=> ActiveRecord::Delegation
2.1.2 :009 > ActiveRecord::Delegation.instance_methods.grep /each/
=> [:each]
現在,您將獲得提示 , 提示來自何處。 其余的可以通過瀏覽源代碼來回答。 Method#owner
可以將您引向正確的路徑。 畢竟這是非常方便的方法 。
現在看這line
。
delegate :to_xml, :to_yaml, :length, :collect, :map, :each ....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.