mysql - Rails 4 相当于 SQL "select count"?

标签 mysql ruby-on-rails ruby-on-rails-4

我有一个 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 %>

我知道有一种更有效的方法来获取该数字。有人可以帮我吗?

最佳答案

Rails docs say to do this:

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/

相关文章:

python - mysqlfailover : No module named mysql. utilities.common.tools

ruby-on-rails - ActsAsTaggableOn 未定义方法 '[]=' 为 nil :NilClass - Create Action

ruby-on-rails - 从多个模型访问变量

ruby-on-rails - 如何使用 "nested"或 `namespace`/`scope :module` 路由 `scope :path` 路径?

ruby-on-rails - 我需要为这里的错误 : "undefined method ` items' for #<Order:0x00007f93d361b390>"重新装腔作势

ruby-on-rails - rails : unexpected behaviour in Chrome and Firefox when refreshing invalid form page

php - bbCode,添加笑脸?

python - 如何在docker容器内使用python子进程执行mysql命令

Mysql 选择字段中的值

ruby-on-rails - 安装 New Relic 而不向 repo 添加许可证 key