ruby - Source of the New and Create Methods in Rails ActiveRecord while using Associations -


i wondering source (i.e., defining class or module) of new , create methods while using associations in rails.

for example, associations section of rails guides provides case:

class customer < activerecord::base   has_many :orders, :dependent => :destroy end  class order < activerecord::base   belongs_to :customer end 

and enters command in console:

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

(link rails guides section: http://guides.rubyonrails.org/association_basics.html)

but when type this:

@customer.orders.method(:create) 

i error:

undefined method `create' class `array' 

you should have @ collection_proxy.rb here - https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/collection_proxy.rb
start seeing line 204, adequately explains how rails magically comes out methods build , create in associations.

they part of associations module , collectionproxy class.

edit:
of these dynamic methods arrive in rails, metaprogramming abilities in ruby. @customer.orders associations, collectionproxy class included in module , supplies these instance methods.

@foo = @customer.orders @foo.included_modules  #=> list of `activerecord` , `activemodel` modules, includes. @foo.include? activerecord::associations #=> true 

thus, @foo gets honor methods build , create present there, unlike, array object.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -