How to Use the Rails where Method

09/20/2021

Contents

In this article, you will learn how to use the Rails where method.

Rails where Method

The where method in Ruby on Rails allows you to query the database for records that match specific conditions. It is a very useful method that can be used in a variety of ways.

Here are some examples of how to use the where method:

Find all records with a specific attribute value

@users = User.where(name: "John")

This will find all records in the users table where the name attribute is “John”.

Find all records that match multiple conditions

@users = User.where(name: "John", age: 30)

This will find all records in the users table where the name attribute is “John” and the age attribute is 30.

Use comparison operators

@users = User.where("age > ?", 30)

This will find all records in the users table where the age attribute is greater than 30.

Use logical operators

@users = User.where("name = ? OR name = ?", "John", "Jane")

This will find all records in the users table where the name attribute is either “John” or “Jane”.

Use conditions based on associations

@users = User.joins(:posts).where(posts: { category: "news" })

This will find all records in the users table who have a post with a category attribute that is “news”.

Note: the joins method is used here to join the users and posts tables together.