How does ActiveRecord detect the last method call in a chain?

Let me introduce this to you.

class Product < ActiveRecord::Base
end

Product.first.title
#=> "My sample product"

Nothing extraordinary here. Just a simple method call. Now consider the following example.

class Product < ActiveRecord::Base
  def method_missing
  end
end

Product.first.title
#=> nil

Product.first
Product.first.title
#=> "My sample product"

How is this possible? To some extent, they determine the end of the chain of methods and act on it? At least that's my theory.

Can anyone explain this behavior?

+5
source share
1 answer

You see a use artifact irbfor researching things.

When you say this:

> Product.first.title
#=> nil

Yours method_missingwill be called for the lazy loading method title, and you will receive nil.

When you say this:

> Product.first

You do this effectively:

> p = Product.first; puts p.inspect

, irb inspect , AR . title. , :

> Product.first
> Product.first.title

method_missing , Product.first.title title.

:

> Product.first; nil
> Product.first.title

nil s.


, ActiveRecord , , , .

where, order , ActiveRecord:: Relation , . , where ( ActiveRecord:: Relation, ActiveRecord:: QueryMethods) :

def where(opts, *rest)
  return self if opts.blank?

  relation = clone
  relation.where_values += build_where(opts, rest)
  relation
end

, .

first, last, to_a, all, Enumerable ( .. each),... , ActiveRecord . , ActiveRecord::Relation#to_a :

def to_a
  logging_query_plan do
    exec_queries
  end
end

all - , to_a.

ActiveRecord , , , , , , .

+7

All Articles