2011-03-11 54 views
0

我正在使用Ruby on Rails 3,我想解決計數數組中ActiveRecord實例的問題。計數數組中的ActiveRecord實例時遇到問題


我有這樣的代碼

data = Account.where({:name => "Test_name", :city => "Test_city"}).limit(10) 

data調試是

#<Account:0x000001029d2da0>#<Account:0x000001029d2c60>#<Account:0x000001029d2bc0>#<Account:0x000001029d2b20> 

data檢查是

"[#<Account name: \"Test_name\", city: \"Test_city\">, #<Account … >, #<Account id… >, …]" 

懷疑## < ...>應該是類似#<Account...>,#<Account...>,<...>(注意逗號)?


如果在我的代碼我用下面的

data_count = data.count 

data_count

nil 

爲什麼nil?我應該如何計算帳戶?


  • 如果我使用result = data.classresult調試是nil,但如果我用result = data.class調試是"{\"inheritable_attributes\":{}}"
  • 如果我使用Account.find_by_name("Test_name")而不是Account.where(...),我會得到與上面相同的結果。
+0

我無法複製這個。 – 2011-03-11 06:51:10

+0

@安德魯馬歇爾爲什麼? : - \ – user502052 2011-03-11 06:55:40

+0

當我在我自己的項目中的某個模型上完成這項工作時,我從'count'中得到預期結果。請在Rails控制檯中運行您的代碼,並從那裏準確地發佈您的會話。 – 2011-03-11 07:00:11

回答

0

要到底層的東西,與啓動rails控制檯:

 
$ rails c 

由於賬戶是一個ActiveRecord模型,你應該可以在rails控制檯中執行以下操作:

 
> Account.all.count 
=> 100 
> Account.where(:status=>'active') 
=> [ #<Account id: 1, name: "a1", ...>, #<Account id: 2, name: "a2", ...>, #<Account id: 3, name: "a3", ...>, ...] 

我在這裏揮舞着很多手......因爲我不知道你的模式。用適合您情況的任何工作替換where條件。返回值應該看起來像一個數組,其中包含數據庫中與條件匹配的所有行的列表。順便說一句,數組是元素的列表,並檢查(以及在控制檯中的默認顯示)show元素用逗號分隔。我沒有使用調試,所以我不能評論它應該做什麼。

您可以驗證返回值是否爲AREL,並且應該可以執行其他一些操作來驗證事情是否按預期工作。

 
> Account.where(:status=>'active').class 
=> ActiveRecord::Relation 
> Account.where(:status=>'active').size 
=> 99 
> Account.where(:status=>'active').count 
=> 99 
> Account.where(:status=>'active').limit(10).count 
=> 10 

如果這些在控制檯中按預期工作,那麼視圖中可能會有某些東西妨礙了正確的行爲。在這種情況下,您需要發佈視圖代碼的詳細信息。如果在控制檯中仍然存在奇怪的行爲,我會建議發佈仍然存在問題的實際模型代碼的最小部分,以及遷移,以便我們可以看到該模式。

+0

我用inspect更新了這個問題'data。 size'return'nil。我沒有使用命名範圍 – user502052 2011-03-11 07:55:04

+0

'debug'是指在視圖文件中<=%debug data%>。'data_count = data.count.to_json'的輸出是「{\ inheritable_attributes \「:{}}」。請注意,如果我不使用'to_json',我會得到一個零值。 – user502052 2011-03-11 09:41:52

0

我認爲你在哪裏有一些問題的情況。 你能顯示where子句中使用的屬性值嗎? 對我來說,它的做工精細:

data = Account.where('id != 0').limit(10) 
data_count = data.count 
+0

@Ashish我有'{:id => 2,:email =>「[email protected]」}' – user502052 2011-03-11 07:12:11

+0

如果你的where子句中有id,那麼它將只返回一條記錄:)。無論如何嘗試通過data.class – Ashish 2011-03-11 07:18:23

+0

@Ashish打印數據類如果我做'data.class',那麼調試是'零'。 – user502052 2011-03-11 07:25:09