About some Active Record methods or what you may forgot about Active Record

def ip_segment_needed?
targeting_strategies.single.that_are_archived.where('ip_addresses = ?, true).present? && ip_addresses.present?
  1. Less number of calls to the database
  2. Less the memory allocations
  3. Less the duration of complete the operation

Let’s overview some Active Records methods to improve your application performance

Count and Size

def count(column_name = nil)  if block_given?    ………    return super()  end
calculate(:count, column_name)
def size  loaded? ? @records.length : count(:all)end
  • count always makes a database query
  • call size If the data is already loaded
  • or always use size, it makes the database query only if the association is not loaded

Present? and Blank?

def blank?    
respond_to?(:empty?) ? !!empty? : !self
def present?
  • It generates SQL, e.g. SELECT "users".* FROM "users"
  • The result is Memorized
  • It allows to not run a query if it already loaded
  • But should not be used if the ActiveRecord::Relation will never be used in its entirety after present? or blank?

    Example of good using (in that case all relations were uploaded only in the first string):
@relation.first(3).each ...


  • It generates SQL: SELECT 1 AS one FROM "users" LIMIT 1
  • Not memorized. At all
  • Always runs queries. Doesn’t loaded a query
  • Would be better off using present? or blank?
- if @users.exists? # SELECT 1 ...  = @users.size # COUNT ...- if @users.exists? # SELECT 1 ...- @users.each do |user| # loads the entire relation  ...

Any? None? Empty?

def any?  return super if block_given?
def none? return super if block_given? empty?end
def empty? return @records.empty? if loaded? !exists?end
@users.each if @users.any?# There’re actually two queries:@users.any? # (SELECT 1 AS one FROM ... LIMIT 1)@users.each # (SELECT "users".* FROM "users" WHERE ...)
@users.each if @users.any?# Should be replaced with:@users.each if If @users.present?or@users.first(3).each if @users.any?or @users.each if @users.load.any?


class User < ActiveRecord::Base  def active_comments    comments.where(active: true)  endend
class User  has_many :comments  has_many :active_comments, -> { active }, class_name: "Comment"endclass Comment  belongs_to :user  scope :active, -> { where(active: true) }endclass UsersController  def index    @users = User.includes(:active_comments)  endend

Quick tips

  • includes to avoid n+1
  • find_each when loading a large amount of records
    increments number of queries => reduce memory on loading a huge number of records
  • Check existence of a record with exists? Instead of present?
  • Prefer ActiveRecord::Relation#size over ActiveRecord::Calculations#count


  • try to keep the number of SQL queries to a minimum
  • try to use preloaded queries
  • database is always faster than Ruby in retrieving, parsing, or processing data

To read




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Serving Structured Data in Alluxio: Example

BitCherry Weekly Report (2020.08.10~08.16)International Version

A Titanic Struggle for Developer Mindshare Between Node.js and Java

A Titanic Struggle for Developer Mindshare Between Node.js and Java

The Results for 2019 are in: Here are the Key Takeaways from Stack Overflow’s Developer Survey

Guide to Data Synchronization in Microsoft SQL Server

What if we add some CSS animations to our page?

Unclogging our Database: PDFs in Postgres

How did Git get its name?

How did Git get its name banner

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


More from Medium

An Introduction to Computer Networks, Part 1

What is an IR-cut filter — and why do embedded vision applications need it?

Async/await inference in Firefly