Ruby Datamapper counter not working

From irb when I do:

Router.all(:email=>" blake@gmail.com ") 

I get a list of all routers associated with this letter. But when I do this:

 Router.count(:email=>" blake@gmail.com ") 

I always get 0

I also looked at this question: Ruby Datamapper.count always returns 0 , but I still don't know why it doesn't work.

- Update # 1 -

Here is the result of the Router.all command. As you can see, I am returning the results.

 1.9.3-p362 :003 > Router.all(:email=>" blake@gmail.com ") => [#<Router @id=8 @email=" blake@gmail.com " @hostname="router0">, #<Router @id=9 @email=" blake@gmail.com " @hostname="router0">, #<Router @id=10 @email=" blake@gmail.com " @hostname="router0">, #<Router @id=11 @email=" blake@gmail.com " @hostname="router0">, #<Router @id=13 @email=" blake@gmail.com " @hostname="router0">, #<Router @id=14 @email=" blake@gmail.com " @hostname="router0">, #<Router @id=15 @email=" blake@gmail.com " @hostname="router0">, #<Router @id=16 @email=" blake@gmail.com " @hostname="router0">] 

But when I do Router.count as suggested, it still returns 0

 1.9.3-p362 :004 > Router.count(:conditions => ["email = ?", " blake@gmail.com "]) => 0 1.9.3-p362 :005 > Router.count(:conditions => "email = ' blake@gmail.com '") => 0 
+3
source share
2 answers

As piyush noted, Router.all(:email=>" blake@gmail.com ").count is the right way. DataMapper does not start the actual query before you call one of the trigger methods, for example, all , first , last . This allows you to link multiple methods before calling the final .all to execute a complex query.

In the case of Router.count(:email=>" blake@gmail.com ") you use the counter for the "empty" DataMapper object that was initialized, but whose request has not yet been launched.

+1
source

You can require 'dm-aggregates' , after which you can do

 Router.count(:email => " blake@gmail.com ") 

and he is converted to

 SELECT COUNT(*) FROM routers WHERE "email" = ' blake@gmail.com ' 

(Although you will get the same operator with Router.all(:email => " blake@gmail.com ").count with dm-aggregates .)

+1
source

All Articles