.where with several conditions at once
Picking up from find_by
The lesson "find_by: the same idea, without the crash" in ActiveRecord: finding records showed the basic shape. Article.find_by(title: "Nonexistent") looks up one attribute and returns nil when nothing matches. That lesson left the rest for a later course: find_by with several conditions, chaining it with other query methods, and everything .where can do. This is that course.
Two conditions, one query, both required
ScratchArticleQ.where(category: "ruby", published: true)
# => only "Hello Rails", the one row matching both conditions
The scratch table had four rows, and only one was both category: "ruby" and published: true. .where with a hash of several keys joins the conditions with AND: a row has to meet all of them to come back.
The SQL it generates
ScratchArticleQ.where(category: "ruby", published: true).to_sql
# SELECT "scratch_articles_q".* FROM "scratch_articles_q"
# WHERE "scratch_articles_q"."category" = 'ruby'
# AND "scratch_articles_q"."published" = TRUE
.to_sql shows the query: every extra key in the hash becomes another AND condition in the WHERE clause. SQL: where & operators covers what WHERE ... AND ... means in raw SQL. This is the same logic, written as a Ruby hash instead of typed by hand.
Key takeaways
- ActiveRecord: finding records covered
find_bywith one attribute andnilon a miss. This course covers what it left open: everything.wherecan do, andfind_bywith several conditions. .wherewith a multi-key hash joins every condition with AND, so a row must meet all of them to appear.- In the generated SQL, each extra hash key is another AND condition, the same
WHERE ... AND ...logic SQL: where & operators covers in raw SQL.
Keep going with lesson 2
Ranges and arrays: BETWEEN and IN, in Ruby
A Range value generates BETWEEN and an Array value generates IN, both still joined with AND to other keys.
A free account also gives you the quizzes, your progress and notes, and the discussion.