Rails 4 相当于 SQL "select count" ?



我在SQL中有一个查询:

SELECT Foreign_id, Type, COUNT(Type) FROM events GROUP BY Type, Foreign_id

显然,Foreign_id是外键(和另一个表的主键),而 Type 是事件类型的描述符。 此查询在我在 MYSQL 服务器上使用的 SQL 客户端中运行时,会准确返回我正在寻找的内容。

我想知道在 Rails 控制器中运行它的最有效方法(有大量记录)。 现在我不知道如何在 Rails 中将其转换为单个命令。 这是我在控制器中的内容:

@foreign = Foreign.all

然后,我在视图中使用它:

<% foreign.each do |foreign| %>
  <%= foreign.events.select{|event| event.Type == 'A'}.size %><br />
  <%= foreign.events.select{|event| event.Type == 'B'}.size %>
  ...
<% end %>

我知道有一种方法可以更有效地获得这个数字。 有人可以帮助我吗?

Rails 文档说要这样做:

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()

如果只有 2 个types,这将是合适的:

<% @foreigns.each do |foreign| %>
  <%= foreign.events.where( type: 'A' ).count %><br />
  <%= foreign.events.where( type: 'B' ).count %>
<% end %>

最新更新