0
0
Ruby on Railsframework~5 mins

Where conditions in Ruby on Rails

Choose your learning style9 modes available
Introduction

Where conditions help you find specific records in a database by filtering data based on rules.

When you want to get users who live in a certain city.
When you need to find orders with a total price above a certain amount.
When you want to list products that are in stock.
When you want to filter blog posts published after a certain date.
Syntax
Ruby on Rails
Model.where(attribute: value)
Model.where("attribute > ?", value)
Model.where("attribute LIKE ?", "%value%")

You can pass a hash for simple equality checks.

Use strings with placeholders for more complex conditions.

Examples
Finds all users with the name 'Alice'.
Ruby on Rails
User.where(name: "Alice")
Finds orders where the total price is greater than 100.
Ruby on Rails
Order.where("total_price > ?", 100)
Finds products with 'book' anywhere in their name.
Ruby on Rails
Product.where("name LIKE ?", "%book%")
Sample Program

This example finds all users who are 18 years old or older and prints their names with a message.

Ruby on Rails
class User < ApplicationRecord
end

# Find users aged 18 or older
adult_users = User.where("age >= ?", 18)
adult_users.each do |user|
  puts "#{user.name} is an adult."
end
OutputSuccess
Important Notes

Where returns an ActiveRecord::Relation, so you can chain more queries.

Using placeholders (?) helps prevent SQL injection.

Conditions can be combined with .where multiple times.

Summary

Use where to filter database records by conditions.

Pass hashes for simple checks or strings with placeholders for complex queries.

Where returns a chainable query object.