I have a table with about 500,000 users in it. When I use my Rails 3.0 console and type
User.first
I get the result immediately. But when I type
User.first(1)
it takes several seconds. What could be causing this?
Note: the same thing happens between
User.last
and
User.last(1)
I turned on log displaying in Erb (Rails 3.0.7) and yield following
So we can see that when you call
firstwithout arguments it works as expected, but when we callfirstwith anumberas argument it loads all users for DB and then leave onlynumberelements in users array.In recent Rails code of
firstlooks like thisSo it is quite ok. But in older version like Rails 3.0.7 it is:
So as you can see if
firstargument isIntegerActiveRecord load all data, convert it into array and call Array’sfirstmethod, which has following behaviour: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-first