DEV Community

April Skrine
April Skrine

Posted on • Updated on

Cheat Sheet: ActiveRecord QueryMethods

.count

  • Return value: integer
  • Counts total of instances, or # of values in an array

Order.count


.create

  • Return value: New created instance of a class
Order.create(name: "Americano", price: 5.55)
Enter fullscreen mode Exit fullscreen mode

.pluck

  • Return value: an array of values grabbed that match the plucked column names
  • Extremely helpful when used with other selectors
Person.pluck(:name)
# SELECT people.name FROM people
# => ['David', 'Jeremy', 'Jose']

Person.pluck(:id, :name)
# SELECT people.id, people.name FROM people
# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]

Person.distinct.pluck(:role)
# SELECT DISTINCT role FROM people
# => ['admin', 'member', 'guest']

Person.where(age: 21).limit(5).pluck(:id)
# SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
# => [2, 3]
Enter fullscreen mode Exit fullscreen mode

.sum

  • Return value: integer
  • Calculates the sum of a column

Person.sum(:age) # => 4562


.maximum & .minimum

  • Return value: integer
  • Finds the max/min value of a table column

Person.maximum(:age) # => 93
Person.minimum(:age) # => 93


.where

  • Return value: Instance(s) of class
  • Can take various arguments, including a string, array or hash. A single string is often 1 argument, and an array can be used for multiple arguments, where the first element in the array is treated as a template. It can also accept a hash, with the key/value pairs you're looking for.

String example:
Client.where("orders_count = '2'")

Array example:
User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])

Hash example:
User.where({ name: "Joe", email: "joe@example.com" })


.max_by & min_by

  • Return value: enumerator
  • Good to use in methods, as its return value by itself is not a common wanted value. Looks for either the min/max values
Coffee.all.max_by{ |c| c.orders.size}
Coffee.all.min_by{ |c| c.orders.size}
Enter fullscreen mode Exit fullscreen mode

.first & .last

  • Return value: Instance of class
  • Very useful in conjunction with .sort

Order.all.sort.last


Sources: rubydoc.info

Top comments (0)