Share This Article
The where
ActiveRecord method is one of the most powerful features this ORM offers. It allows you to express your conditions as simple key-value pairs, making your code more readable & shielded from SQL injection attacks. Here’s a quick overview of how to use it:
User.where(name: "John")
The where
method will return an array of matching records.
If you want to retrieve a single record you can use the first
method:
User.where(name: "John").first
You can also specify multiple conditions using the and
method:
User.where("name = ? and age = ?", "John", 20)
The above code will generate the following SQL:
sql
SELECT * FROM users WHERE name = 'John' AND age = 20
You can also use the or
method:
User.where("name = ? or age = ?", "John", 20)
The above code will generate the following SQL:
sql
SELECT * FROM users WHERE name = 'John' OR age = 20
Specifying a Limit
You can use the limit
method to specify the maximum number of records to return.
Example:
User.where(name: "John").limit(5)
This will generate the following SQL:
sql
SELECT * FROM users WHERE name = 'John' LIMIT 5
Ordering Results
You can use the order
method to specify the order in which records are returned.
The order
method accepts a column name & an optional direction (asc
or desc
).
Example:
User.where(name: "John").order("age asc")
Specifying a Default Order
If you want to specify a default order, you can use the default_scope
method.
Example:
class User < ActiveRecord::Base
default_scope { order("name asc") }
end
Specifying a Custom SQL
You can use the find_by_sql
method to specify a SQL query.
Example:
User.find_by_sql("SELECT * FROM users WHERE name = 'John'")
You can also use the pluck
method to specify the columns you want to retrieve.
Summary
In this article, you’ve learned how to use the ActiveRecord where
limit
, order
and default_scope
methods to manipulate the results.
This is just the tip of the iceberg. If you want to learn more about the different ways you can use where
, we invite you to read the ActiveRecord where documentation.