3

From irb when I do:

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

I get a list of all the routers associated with that email. But when I do:

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

I always get 0

I've also looked at this question: Ruby Datamapper .count always returns 0 but I still don't know why it isn't working.

-- Update #1 --

Here is the output of the Router.all command. As you can see I get results back.

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 is returning 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 
Community
  • 1
  • 1
Blake Erickson
  • 755
  • 1
  • 9
  • 28

2 Answers2

1

As piyush pointed out, Router.all(:email=>"blake@gmail.com").count is the right way. DataMapper doesn't run the actual query before you call one of the "trigger" methods, such as all, first, last. This allows chaining several methods before calling a final .all to run the compound query.

In case of Router.count(:email=>"blake@gmail.com"), you're running a count on an "empty" DataMapper object, one that's been initialized but whose query hasn't run yet.

Arman H
  • 5,488
  • 10
  • 51
  • 76
1

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

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

and it'll get transformed into

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

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

morbusg
  • 1,319
  • 2
  • 11
  • 20