[英]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.