Search code examples
ruby-on-railsrubyassociationsmodels

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


I was wondering what the source (i.e., defining class or module) of the New and Create methods is while using associations in Rails.

For example, the Associations section of the Rails guides provides this case:

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

class Order < ActiveRecord::Base
  belongs_to :customer
end

And then enters this command in the console:

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

(Link to Rails Guides section: http://guides.rubyonrails.org/association_basics.html)

But when I type this:

@customer.orders.method(:create)

I get the error:

undefined method `create' for class `Array'

Solution

  • You should have a look at collection_proxy.rb here - https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/collection_proxy.rb
    Start seeing from Line 204, it adequately explains how Rails magically comes out with methods like build and create in associations.

    They are part of Associations module and CollectionProxy class.

    EDIT:
    Most of these dynamic methods arrive in Rails, thanks to metaprogramming abilities in Ruby. @customer.orders is also a Associations, CollectionProxy is a class included in this module and thus supplies these instance methods.

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

    Thus, @foo gets the honor with methods like build and create which are present there, unlike, just another Array object.