2013-05-13 54 views
0

我想知道在Rails中使用關聯時New和Create方法的源(即定義類或模塊)是什麼。使用關聯時新建和創建方法的Rails ActiveRecord的來源

例如,導軌導向件的關聯部分提供了這種情況:

class Customer < ActiveRecord::Base 
    has_many :orders, :dependent => :destroy 
end 

class Order < ActiveRecord::Base 
    belongs_to :customer 
end 

然後在控制檯輸入該命令:

@order = @customer.orders.create(:order_date => Time.now) 

(鏈接到導軌指南部分:http://guides.rubyonrails.org/association_basics.html

但是當我輸入這個:

@customer.orders.method(:create) 

我得到的錯誤:

undefined method `create' for class `Array' 
+0

訂單類中是否有創建方法? – 2013-05-13 06:52:38

+0

選中此項:http://stackoverflow.com/a/10430216/1322562 – jdoe 2013-05-13 06:57:06

回答

0

你應該看看collection_proxy.rb這裏 - https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/collection_proxy.rb
開始從看到204線,這充分說明了如何的鋼軌奇蹟般地出現與像buildcreate方法在協會。

它們是Associations模塊和CollectionProxy類的一部分。

編輯:
大多數這些動態方法在Rails的到來,由於在Ruby中metaprogramming能力。 @customer.orders也是Associations,CollectionProxy是包含在此模塊中的類,因此提供了這些實例方法。

@foo = @customer.orders 
@foo.included_modules 
#=> List of all `ActiveRecord` and `ActiveModel` modules, it includes. 
@foo.include? ActiveRecord::Associations 
#=> True 

因此,@foo得到與像buildcreate方法中存在有,不同的是,只是另一個Array對象榮譽。

+0

你能給出一些關於魔法如何發生的解釋嗎?在閱讀Rails源代碼時,我仍然需要一些練習,所以對於我來說資源對其他人來說不是那麼有幫助。我仍然對如何在數組的實例中調用new或創建時感到困惑,因爲Array類似乎沒有混入其中的任何一種方法。 – voltair 2013-05-13 19:24:37

+0

添加了上面的信息。 – kiddorails 2013-05-13 19:40:05