Last Updated: February 25, 2016
·
686
· stuliston

Doctor, doctor; Why is my ActiveRecord scope eager-loading?

Whilst refactoring out a Query Object (explained in the excellent @codeclimate blog post 7 Patterns to Refactor Fat ActiveRecord Models), I came across a weird issue where my scoped model was eagerly loading.

E.g.

irb(main):029:0> User.scoped
User Load (248.5ms)  SELECT "users".* FROM "users"
.... SQLWTF!!1!

After pondering this for a while, and reading the docs, I realised the problem was that the console I was testing in wants to inspect the last statement, and therefore it was executing the scope.

You can get around this by popping something else at the end of the statement for the console to evaluate:

irb(main):030:0> u = User.scoped; nil
=> nil
irb(main):031:0> u.count
(78.1ms)  SELECT COUNT(*) FROM "users"
=> 909164

BOOM!