[英]How to count total string value / group using an Active Record query?
[英]How do I count the number of records in a group using Active Record?
我有一个文件列表和这些文件中的单词列表。 foreign_key是字段filenum
。 一个文件可以有多个单词出现,因此wordtable可以针对一个单词的不同单词位置具有许多filetable条目。
我的活动记录类是:
class File1 < ActiveRecord::Base
self.table_name = :filetable
self.primary_key = :FileNum
belongs_to :word
end
class Word < ActiveRecord::Base
self.table_name = :wordtable
self.primary_key = :fileNum
has_one :file1, foreign_key: :filenum, primary_key: :filenum
end
我的查询是:
query = 'ole'
Word.where(['name LIKE ?', "%#{query}%"]).group(:fileNum).each do |word, occurences|
printf "%-24s %12s %12s\n" % [word.name, word.file1.FilePath, occurences]
end
这是我当前结果的一部分:
ole C:\Users\user\ruby\_nakijken\stringbuilder_list_properties.rb
boolean C:\Users\user\ruby\_nakijken\s_pinger.rb
console C:\Users\user\ruby\_nakijken\s_transition.rb
ole C:\Users\user\ruby\_nakijken\save_outlook_message.rb
...
该查询有效,但发生的总数除外。 我想知道那个单词在该文件中出现的次数。 我应该怎么做?
就目前而言,id做起来有点丑陋
query = 'require'
name, filenum, count, filepath = '', 0, 0, ''
Word.where(['name LIKE ?', "%#{query}%"]).group(:name, :filenum, :position).each do |word|
if filenum == 0
name, filenum, count, filepath = word.name, word.filenum, 1, word.file1.FilePath
elsif name == word.name && filenum == word.filenum
count += 1
else
printf "%-24s %12s (%s)\n" % [name, filepath, count]
name, filenum, count, filepath = word.name, word.filenum, 1, word.file1.FilePath
end
end
if filenum == 0
puts "'#{query}' not found"
else
printf "%-24s %12s (%s)\n" % [name, filepath, count]
end
查看文档 :
如果
count
与group
,它将返回一个Hash
其键表示聚合的列,并且值分别是各自的数量:Person.group(:city).count # => { 'Rome' => 5, 'Paris' => 3 }
看来您应该在查询中添加count
:
query = 'ole'
Word.where(['name LIKE ?', "%#{query}%"]).group(:fileNum).count.each do |fileNum, occurences|
# ...
end
对于您当前的解决方案(因为我的解决方案似乎无法正常工作),我可以使用group_by
建议一个更group_by
版本:
grouped_words = Word.where(['name LIKE ?', "%#{query}%"]).group(:name, :filenum, :position)
grouped_words.group_by { |group| [group.name, group.filenum] }.each do |(name, _), words|
printf "%-24s %12s (%s)\n" % [name, words.first.file1.FilePath, words.count]
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.