我有一个 SQL 查询:
SELECT Foreign_id, Type, COUNT(Type) FROM events GROUP BY Type, Foreign_id
Foreign_id 显然是外键(也是另一个表的主键),Type 是事件类型的描述符。当我在 MYSQL 服务器上使用的 SQL 客户端中运行此查询时,该查询将准确返回我正在查找的内容。
我想知道在 Rails Controller 中运行它的最有效方法(有大量记录)。现在我不知道如何将其变成 Rails 中的单个命令。这是我的 Controller 中的内容:
@foreign = Foreign.all
然后我在 View 中使用它:
<% foreign.each do |foreign| %>
<%= foreign.events.select{|event| event.Type == 'A'}.size %><br />
<%= foreign.events.select{|event| event.Type == 'B'}.size %>
...
<% end %>
我知道有一种更有效的方法来获取该数字。有人可以帮我吗?
最佳答案
Person.count
# => the total count of all people
Person.count(:age)
# => returns the total count of all people whose age is present in database
Person.count(:all)
# => performs a COUNT(*) (:all is an alias for '*')
Person.distinct.count(:age)
# => counts the number of different age values
Person.group(:city).count
# => { 'Rome' => 5, 'Paris' => 3 }
Article.group(:status, :category).count
# => {["draft", "business"]=>10, ["draft", "technology"]=>4, ["published", "business"]=>0, ["published", "technology"]=>2}
Person.select(:age).count
# => counts the number of different age values
所以在你的情况下,我相信你会这样做:
@foreign = Foreign.events.select('Type','A').count()
关于mysql - Rails 4 相当于 SQL "select count"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35929822/