2011-03-11 50 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