Introduction
Where conditions help you find specific records in a database by filtering data based on rules.
Where conditions help you find specific records in a database by filtering data based on rules.
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.
User.where(name: "Alice")Order.where("total_price > ?", 100)
Product.where("name LIKE ?", "%book%")
This example finds all users who are 18 years old or older and prints their names with a message.
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
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.
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.
where method do in Rails ActiveRecord?wherewhere method is used to specify conditions to filter records in a database query.delete, migrations, or update_all.where?age: 30 is the standard way to filter by attribute value.User.where("name LIKE ?", "%John%")User.where(age > 25)
User.where("age > ?", 25) or User.where("age > 25").where conditions to find users who are active and older than 18?Pass the test and this pattern moves unknown