This is expected. The three ways to get the size of an ActiveRecord
collection are:
.count #=> this always triggers a SELECT COUNT(*) on the database
.size #=> if the collection has been loaded, defers to
Enumerable#size, else does the SELECT COUNT(*)
.length #=> always loads the collection and then defers to
Enumerable#size (I think it's length, but I don't think I ever used it
:P)
So, since Post.popular doesn't trigger the query and load the objects,
calling size will do a count query.
This is, apparently, a good use case for Post.popular.length :)
Cheers,
-foca
> Best regards,
> DBA
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To unsubscribe from this group, send email to rubyonrails-co...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
>
>
Or a good reason to change the code to do:
SELECT COUNT(*) FROM (SELECT `posts`.* FROM `posts` ORDER BY views
desc LIMIT 5) AS some_alias
which is Sequel's behavior.
Jeremy
I'm not sure that would be the right things to do. The #count/#size/#length has been a documented feature of AR for as long as I can remember changing it on any scope does not sound like a good idea to me.
- Ken
Funny you should mention this. I just finished up the parts of the SqlserverCompiler that deal with taking the limit/offset (taken/skipped) and wrapping up all the clauses for a lean count. Basically passing a few tests the adapter was failing in RelationTest. I added these just to make sure I was in parity with the MysqlCompiler.
Notice how I use #size because I know from the ActiveRecord docs and tests that this issues a count anyway.