【问题标题】:How to count total string value / group using an Active Record query?如何使用 Active Record 查询计算总字符串值/组?
【发布时间】:2017-06-04 12:21:21
【问题描述】:

有没有办法使用 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 执行此操作?我在想我可以使用枚举进行迭代,但这不是解决这种情况的最佳方法。

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

【问题讨论】:

    标签: ruby-on-rails ruby postgresql activerecord ruby-on-rails-5


    【解决方案1】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-06
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      相关资源
      最近更新 更多