如何使用 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
有没有一种方法可以使用 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