Skip to content

Commit e4214dd

Browse files
pirjbbatsov
authored andcommitted
Recommend using where with ranges
1 parent 65c8789 commit e4214dd

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

README.adoc

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1041,6 +1041,33 @@ User.all.size
10411041
User.all.length
10421042
----
10431043

1044+
=== Where with Ranges [[where-ranges]]
1045+
1046+
Use ranges instead of defining comparative conditions using a template for scalar values.
1047+
1048+
[source,ruby]
1049+
----
1050+
# bad
1051+
User.where("created_at > ?", 30.days.ago).where("created_at < ?", 7.days.ago)
1052+
User.where("created_at > ? AND created_at < ?", 30.days.ago, 7.days.ago)
1053+
User.where("created_at > :start AND created_at < end", start: 30.days.ago, end: 7.days.ago)
1054+
1055+
# good
1056+
User.where(created_at: 30.days.ago..7.days.ago)
1057+
1058+
# bad
1059+
User.where("created_at > ?", 7.days.ago)
1060+
1061+
# good
1062+
User.where(created_at: 7.days.ago..)
1063+
1064+
# okish - there is no range syntax that would denote inclusion on one end and
1065+
# exclusion on another.
1066+
Customer.where("purchases_count > :min AND purchases_count <= :max", min: 0, max: 5)
1067+
----
1068+
1069+
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.
1070+
10441071
== Migrations
10451072

10461073
=== Schema Version [[schema-version]]

0 commit comments

Comments
 (0)