我有一个名为的字段deviceID
,我正在尝试获取数据库(MongoDB)中该字段的唯一值的数量。我正在看这篇SO帖子中的示例,但没有一个对我有用。我正在使用Rails 4.2.2,并且我现在也有以下几行代码在工作:
范例1:
<p id="total">Total number of database entries: <%= DistributedHealth.count %></p>
范例2:
<% @distributed_healths.each do |distributed_health| %>
<tr>
<td><%= distributed_health.deviceID %></td>
</tr>
<% end %>
这些是我为完成此任务而失败的尝试。
尝试#1失败:
<%= DistributedHealth.distinct.count(:deviceID) %>
错误1:
wrong number of arguments (0 for 1)
尝试#2失败:
<%= DistributedHealth.distinct.count('deviceID') %>
错误#2:
wrong number of arguments (0 for 1)
#3尝试失败(我知道这是针对Rails 3的,但是我很绝望):
<%= DistributedHealth.count('deviceID', :distinct => true) %>
错误#3:
wrong number of arguments (2 for 0)
我可以发布任何其他有用的代码,对您的帮助将不胜感激。如果我能正常工作,我将更新此帖子。先感谢您。
克莱顿
编辑1:
从我的Gemfile中:
gem 'mongoid'
gem "moped"
gem 'bson_ext'
解决方案:
就像下面发布的那样,我需要的代码是
DistributedHealth.distinct('deviceID').count
您快到了:
DistributedHealth.distinct('deviceID').count
您想要使用来捕获不同deviceID
的distinct
,然后使用来对它们进行计数Array#count
(或者,Array#length
如果您想提醒自己,您实际上是在对数组中的元素进行计数,而不是直接向数据库查询该计数)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句