繁体   English   中英

如何使用Active Record查询来计算总字符串值/组?

[英]How to count total string value / group using an Active Record query?

有没有一种方法可以使用Active Record(使用PostgreSQL作为数据库)来计算数据库列中有多少个特定的字符串值?

如果要在我的view中显示世界上有多少塔科爱好者。

例如:

# Where the number "2" was an ActiveRecord count in the Persons table
# reading from the column named "favorite_food"

<div class="notice">
  <p>There are 2 burrito lovers online</p>
</div>

通过查看ActiveRecord文档,我了解到了这一点:

# == Schema Information
#
# Table name: Persons
#
#  id                     :integer          not null, primary key
#  name                   :string           default(""), not null
#  age                    :integer          default(""), not null
#  favorite_food          :string

# Data
# Person id: 1, name: "John", age: "18", favorite_food: "taco"
# Person id: 2, name: "Jane", age: "19", favorite_food: "taco"
# Person id: 3, name: "Bill", age: "20", favorite_food: "burrito"
# Person id: 4, name: "Beth", age: "21", favorite_food: "nacho"

# This will record total unique foods
Person.count(:favorite_food)
=> 3

# This will return a hash with total name of distinct foods
Person.group(:favorite_food).count
=> {taco=>"2", "burrito"=>1, "nacho"=>1}

我认为最后一点已经接近了,但我想查询一种特定的食物类型,如果可能的话,我将如何使用ActiveRecord进行查询? 我当时以为可以使用枚举进行迭代,但这不是解决这种情况的最佳方法。

感谢您抽出宝贵时间来看看我的问题。

尝试这个

Person.where(favorite_food: 'burrito').count

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM