How to Use The Rails Where Method (With Examples) - RubyGuides

Ask questions Research chat →

https://www.rubyguides.com/2019/07/rails-where-method/ · scraped

rails

Attachments

Scraped Content

— 808 words · 2026-02-14 17:41:45 UTC ·

Excerpt

![](https://prod-files-secure.s3.us-west-2.amazonaws.com/871f1661-80b8-4d0c-ac3b-2adfc6ff4c66/d1387f0a-cbd5-4748-9809-d692a01d5ccd/rails-where-method.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=ASIAZI2LB466V4RKZLI6%2F20260214%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20260214T174145Z&X-Amz-Expires=3600&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEEEaCXVzLXdlc3QtMiJHMEUCIFlKeCai1YmyJQmMSTAsHX%2Bp6xTyKxIjj%2B6qf3dtXnUIAiEApsuy4yOql33P%2BNm2cGgr3w0rqPdnMdoaMUAi8DN0bdoq%2FwMIChAAGgw2Mzc0MjMxODM4MDUiDBRYj4nwneCSZ4123yrcA1B9i%2FXt7KFGFDRko7r3S1a0%2BiTamFJ2efe3HJTeVY556Ls%2FNzizJUIQLXXWh84c8yTgfkD7cbCFJYs5tZ0m3cJabprtXUzB8qTZxb%2Ffntftje8iI9hBQyXM7Aj5D9B%2Bh%2Bo5bPRM9Wm7xoLk76MMhkty35ZXWVOTLEQ3synCp%2BnI%2FGD3HKdWlUdL%2FaEtcSYSgiqVwYGroiccodGsdWwMFnOgH35itUMyQlVdZfdX%2FXF28LJ%2B8clqcly3VcbnWcp14wMRyEuceLNRez4WeT3qG%2BPlZPrcLJ0axcYhHF%2FZNJRrSfsYUsxXp5d%2FairxZcSgEDw0BTeBT813J%2FgpzNKlexIiXLT44RRH1qhC1cfsv%2FwWJpvfRcaJ8K%2B4hAuAaf%2FxOMnbSDXDEvwGCHJZkm
![](https://prod-files-secure.s3.us-west-2.amazonaws.com/871f1661-80b8-4d0c-ac3b-2adfc6ff4c66/d1387f0a-cbd5-4748-9809-d692a01d5ccd/rails-where-method.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=ASIAZI2LB466V4RKZLI6%2F20260214%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20260214T174145Z&X-Amz-Expires=3600&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEEEaCXVzLXdlc3QtMiJHMEUCIFlKeCai1YmyJQmMSTAsHX%2Bp6xTyKxIjj%2B6qf3dtXnUIAiEApsuy4yOql33P%2BNm2cGgr3w0rqPdnMdoaMUAi8DN0bdoq%2FwMIChAAGgw2Mzc0MjMxODM4MDUiDBRYj4nwneCSZ4123yrcA1B9i%2FXt7KFGFDRko7r3S1a0%2BiTamFJ2efe3HJTeVY556Ls%2FNzizJUIQLXXWh84c8yTgfkD7cbCFJYs5tZ0m3cJabprtXUzB8qTZxb%2Ffntftje8iI9hBQyXM7Aj5D9B%2Bh%2Bo5bPRM9Wm7xoLk76MMhkty35ZXWVOTLEQ3synCp%2BnI%2FGD3HKdWlUdL%2FaEtcSYSgiqVwYGroiccodGsdWwMFnOgH35itUMyQlVdZfdX%2FXF28LJ%2B8clqcly3VcbnWcp14wMRyEuceLNRez4WeT3qG%2BPlZPrcLJ0axcYhHF%2FZNJRrSfsYUsxXp5d%2FairxZcSgEDw0BTeBT813J%2FgpzNKlexIiXLT44RRH1qhC1cfsv%2FwWJpvfRcaJ8K%2B4hAuAaf%2FxOMnbSDXDEvwGCHJZkmE0E2Rp09hVloZyAuwt5wRO8Lg1P6%2B0w3tx0uYTXmsBkkX9CES%2BrUui6j0XBsEYLqZ6YwGrbrWfrIc8KfSFwAg8TNlwWQ%2BN2R6rtMRDErnp92aD%2BcfOj1wCU%2F0ra9wqN2%2B7JNtDztgiFrViErRuAZur8Wz%2Bo4j1UtfeArvnG4ko3V2%2B0nJbkJWqk6%2FDYRunaBNYto1TZsdaGiHAKy%2Fgl7XJrONbPdxEj3yvIcI%2BlZTfMMjRwswGOqUB3VHvszvqf3V9RMkQu7j4KuYVwDh6sViYFMH1h5wiQtRGlbRSSXiTn3jSj%2FQHH8EkgEXPQk6JLu2Pcn%2F1ifqlnRmULjUwj%2FBI%2BHkuicNTyn7qDtBEeyiHKiAf0n%2F2W%2FvkTS04aRtC2nQI9MXoyTPNJSAi36rrlhYl9hEeTcaxdwTKtfovsqQw%2BomU9yBtEwsa%2F%2BFLykXvsj4JrlXFlE%2F6G%2FNagoEJ&X-Amz-Signature=465b1b8fad02c69885c45e13d7a5526bd471afe061d8eaac5c3c1dee3cfc700f&X-Amz-SignedHeaders=host&x-amz-checksum-mode=ENABLED&x-id=GetObject) In Rails, you can query the database through your models to access your data. You can do this using ActiveRecord methods. Like where, find, or find_by. As a result you get: - With find_by, a single record or nil - With where, an ActiveRecord::Relation object - With find, a single record, found by its primary column (usually id), raises an exception if not found In other words: If you’re expecting one record (a specific user), use find_by, for multiple records (a list of users) use where. But where has many ways to use it, which often confuses beginners. No problem! We’re going to take a look at the different ways you can use where in your Rails applications. ## Basic Where Conditions The purpose of using where is to build a query that filters the information in your database, so you only get the rows you want. For example: Given a Book model, with title, author & category. You may want to find out all the books by a specific author, or all the books filed under a particular category. Here’s a query: ```plain text Book.where(category: "Ruby") ``` This returns all the books with a category of “Ruby”. You can also combine conditions. Like this: ```plain text Book.where(category: "Ruby", author: "Jesus Castello") ``` This returns books that match both category & author. And you can combine where with a scope. ```plain text # scope definition class Book scope :long_title, -> { where("LENGTH(title) > 20") } end # controller code @books = Book.long_title.where(category: "Ruby") ``` Using a hash (fruit: "apple"), allows you to check if a column is equal to something. But what if you aren’t looking for equality? Then you’ll have to use a string. ## Rails Where: Greater Than & Less Than If you want to check for “greater than”, “less than”, or something like that… Do it like this: ```plain text Book.where("LENGTH(title) > 20") ``` If you need to interpolate values… Do it like this: ```plain text Book.where("LENGTH(title) > ?", params[:min_length]) ``` This ? is called a “placeholder”, and it’s used for security to avoid “SQL injection” attacks. Another option is to use named placeholders. Example: ```plain text Book.where("LENGTH(title) > :min", min: params[:min_length]) ``` I find this less common than the question mark placeholder, but it could be useful for queries involving many interpolated values. ## How to Use Where Not & Where Or Conditions Let’s look at more complex queries. If you want to check that a condition is NOT true, then you can combine where with the not method. Here’s an example: ```plain text Book.where.not(category: "Java") ``` Another example: ```plain text Book.where.not(title: nil) ``` This finds Books with a title that’s not nil. What about an OR condition? You can combine where with the or method to get rows that match ANY of two or more conditions. Here’s how it works: ```plain text Book.where(category: "Programming").or(Book.where(category: "Ruby")) ``` This combines two where queries into one. Give it a try! ## Rails Where IN Array Example All the examples we have seen look for one specific value. But you can look for multiple values. How? Using an array! Example: ```plain text Book.where(id: [1,2,3]) ``` This generates an “IN” query that will search, at the same time, all these ids. ```plain text SELECT "books".* FROM "books" WHERE "books"."id" IN (1, 2, 3) ``` You’ll find this query in the rails logs. ## Rails Joins Association Condition If you’re looking to match based on an association value, you’ll have to make that association available with the joins method. Then you can do this: ```plain text Book.joins(:comments).where(comments: { id: 2 }) ``` With this query you get all the books, which have a comment, and the comment id is 2. For the string version: ```plain text Book.joins(:comments).where("comments.id = 2") ``` Where comments is the table name, and id is column name. ## How to Search Inside Text With A Where LIKE Condition If you want to implement a search function, you may want to allow for a partial match. You can do this with a “LIKE” query. Here’s an example: ```plain text Book.where("title LIKE ?", "%" + params[:q] + "%") ``` This finds all the titles that have the search text, provided by the params (params[:q]), anywhere inside the title. Very helpful query! What’s the percent symbol? In SQL, % is a wildcard character. ## Video: Where vs Find_By in Detail ## Summary You have learned how to use the Rails where method to query your ActiveRecord models! Including: - How to filter by multiple conditions - How to use arrays to find multiple rows efficiently - How to use where in combination with the or & not methods to write more complex queries Now it’s your turn to put this into practice. Thanks for reading 🙂 Amazing article! It helps me improve my rails skils! Many thanks!

Visibility

Visible to everyone

Reading Status

Related Bookmarks

My Note


Saved!

Annotations

Export as Markdown
+ Annotate selection

Add Annotation