Skip to content

Commit

Permalink
Recommend using where with ranges
Browse files Browse the repository at this point in the history
  • Loading branch information
pirj committed May 3, 2022
1 parent 73b9c68 commit bd73b49
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -854,14 +854,14 @@ Consider using named placeholders instead of positional placeholders when you ha
----
# okish
Client.where(
'created_at >= ? AND created_at <= ?',
params[:start_date], params[:end_date]
'orders_count >= ? AND country_code = ?',
params[:min_orders_count], params[:country_code]
)
# good
Client.where(
'created_at >= :start_date AND created_at <= :end_date',
start_date: params[:start_date], end_date: params[:end_date]
'orders_count >= :min_orders_count AND country_code = :country_code',
min_orders_count: params[:min_orders_count], country_code: params[:country_code]
)
----

Expand Down Expand Up @@ -1025,6 +1025,33 @@ User.all.size
User.all.length
----

=== Where with Ranges [[where-ranges]]

Use ranges instead of defining comparative conditions using a template for scalar values.

[source,ruby]
----
# bad
User.where("created_at > ?", 30.days.ago).where("created_at < ?", 7.days.ago)
User.where("created_at > ? AND created_at < ?", 30.days.ago, 7.days.ago)
User.where("created_at > :start AND created_at < end", start: 30.days.ago, end: 7.days.ago)
# good
User.where(created_at: 30.days.ago..7.days.ago)
# bad
User.where("created_at > ?", 7.days.ago)
# good
User.where(created_at: 7.days.ago..)
# okish - there is no range syntax that would denote inclusion on one end and
# exclusion on another.
Customer.where("purchases_count > :min AND purchases_count <= :max", min: 0, max: 5)
----

NOTE: Rails 6.0 or later is required for endless range Ruby 2.6 syntax, and Rails 6.0.3 for beginless range Ruby 2.7 syntax.

== Migrations

=== Schema Version [[schema-version]]
Expand Down

0 comments on commit bd73b49

Please sign in to comment.