.where with several conditions at once

Free preview 2 min to read

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_by with one attribute and nil on a miss. This course covers what it left open: everything .where can do, and find_by with several conditions.
  • .where with 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.
Lesson 1 of 7 · free

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.

Type to start searching...