Is there a way to count how many specific string value from the database column using Active Record (Using PostgreSQL as my database)?
If I wanted to show in my view
the how many taco lovers there are in the world.
For example:
# 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>
From looking around the ActiveRecord documentation I got to this:
# == 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}
I think the last bit is closer but I wanted to query a specific food type, how would I do this with ActiveRecord if this is possible? I was thinking I could iterate using enum but this would be not the best way to tackle this situation.
Thanks for taking the time to take a look at my question.
尝试这个
Person.where(favorite_food: 'burrito').count
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.