Is find() a class method or instance method?

19 views
Skip to first unread message

Warren Zhang

unread,
Jan 6, 2014, 2:53:22 AM1/6/14
to rubyonra...@googlegroups.com
Dear friends,

I came across this code snippet from my reading:


require 'active_record'

class Order < ActiveRecord::Base
end

order = Order.find(1)
...

Looking at: http://api.rubyonrails.org/ and search for find(), find() is
an instance public method. So why can we call Order.find(1) here?
Shouldn't it be Order.new.find(1)?

--
Posted via http://www.ruby-forum.com/.

Frederick Cheung

unread,
Jan 6, 2014, 5:04:35 AM1/6/14
to rubyonra...@googlegroups.com

On Monday, January 6, 2014 7:53:22 AM UTC, Ruby-Forum.com User wrote:

I came across this code snippet from my reading:


    require 'active_record'

    class Order < ActiveRecord::Base
    end

    order = Order.find(1)
    ...

Looking at: http://api.rubyonrails.org/ and search for find(), find() is
an instance public method. So why can we call Order.find(1) here?
Shouldn't it be Order.new.find(1)?


No, because although it is a public instance method, it's a public instance method of ActiveRecord::Relation, not of ActiveRecord::Base. ActiveRecord delegates the find method (and the other querying type methods such as where, first, all etc.) to an instance of this

Fred 
Reply all
Reply to author
Forward
0 new messages