3

私がするときのirbから:

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

そのメールに関連付けられているすべてのルーターのリストを取得します。しかし、私がするとき:

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

私はいつも0を取得します

この質問も見ました: Ruby Datamapper .count は常に 0 を返しますが、なぜそれが機能しないのかはまだわかりません。

-- 更新 #1 --

Router.all コマンドの出力を次に示します。ご覧のとおり、結果が返されます。

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">] 

しかし、提案どおりに Router.count を実行すると、まだ 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 
4

2 に答える 2

1

あなたはできるrequire 'dm-aggregates'、その後できる

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

そしてそれはに変換されます

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

Router.all(:email => "blake@gmail.com").count(ただし、 with を使用しても同じステートメントが得られますdm-aggregates。)

于 2013-03-29T10:10:09.693 に答える
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.

于 2013-03-29T08:42:45.640 に答える