Ruby on rails Rails在多个记录中统计数字数据

Ruby on rails Rails在多个记录中统计数字数据,ruby-on-rails,Ruby On Rails,我的数据库中有一列“事件”。用户可以选择不输入任何内容或输入1到10之间的任何数字。我试图将每个用户的所有事件(跨多个记录)添加到一个总数中 第1部分-筛选当前用户的数据 @total_occurrences = Event.where(['occurrences <> ?', current_user.id]) @total\u events=Event.where(['events?',current\u user.id]) 到目前为止还不错 第2部分-计算“事件”列中的数字

我的数据库中有一列“事件”。用户可以选择不输入任何内容或输入1到10之间的任何数字。我试图将每个用户的所有事件(跨多个记录)添加到一个总数中

第1部分-筛选当前用户的数据

@total_occurrences = Event.where(['occurrences <> ?', current_user.id])
@total\u events=Event.where(['events?',current\u user.id])
到目前为止还不错

第2部分-计算“事件”列中的数字


不确定如何实现这一点…

如果使用rails 4,您可以编写:

@total_occurrences = Event.where(user_id: current_user.id).where.not(occurrences: nil)
在rails 3中,您可以编写sql查询:

@total_occurrences = Event.where(user_id: current_user.id).where("occurrences IS NOT NULL")
或者使用宝石。它允许你这样写:

@total_occurrences = Event.where{(user_id == current_user.id) & (occurrences != nil)}
sum = 0
Event.where(user_id: current_user.id).pluck(:occurrences).each do |occurrence|
  sum += occurrences
end

至于第二部分,您可以这样做:

@total_occurrences = Event.where{(user_id == current_user.id) & (occurrences != nil)}
sum = 0
Event.where(user_id: current_user.id).pluck(:occurrences).each do |occurrence|
  sum += occurrences
end

Pulk提取特定列的所有值,然后只需将它们相加。

brendanjcaffrey的答案就是我想要的:


Event.where(user\u id:current\u user.id).where('occurrents 0').pull(:occurrents).sum

您的where子句正在检查这些事件!=当前用户id。你确定这就是你想要做的吗?请尝试
Event.where(用户标识:当前用户标识)。where('occurrents 0')。pull(:occurrents)。sum