Posted on: Written by: K-Sato
⚠️ This article was posted over 2 years ago. The information might be outdated. ⚠️

Table of Contents

String Conditions

The code below returns clients where the orders_count field’s value is 2.

Client.where("orders_count = '2'")

Array Conditions

When the number could vary, you can write it like the following.

Client.where("orders_count = ?", params[:orders])

Active Record will take the first argument as the conditions string and any additional arguments will replace the question marks (?) in it.

If you want to specify multiple conditions:

Client.where("orders_count = ? AND locked = ?", params[:orders], false)

In this example, the first question mark will be replaced with the value in params[:orders] and the second will be replaced with the SQL representation of false.

The first code is highly preferable to the second code.

# (1)
Client.where("orders_count = ?", params[:orders])
#(2)
Client.where("orders_count = #{params[:orders]}")

because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database as-is. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out they can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.

Scope

Adds a class method for retrieving and querying objects. The method is intended to return an ActiveRecord::Relation object, which is composable with other scopes. If it returns nil or false, an all scope is returned instead.

class Shirt < ActiveRecord::Base
  scope :red, -> { where(color: 'red') }
  scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) }
end

The above calls to scope define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, in effect, represents the query Shirt.where(color: 'red').

Note that this is simply syntactic sugar for defining an actual class method:

class Shirt < ActiveRecord::Base
  def self.red
    where(color: 'red')
  end
end

References

About the author

I am a web-developer based somewhere on earth. I primarily code in TypeScript, Go and Ruby at work. React, RoR and Gin are my go-to Frameworks.