Please note that the PR discussed in this blog was reverted.
Rails 6.1 adds support to comparison operator in the where clause. The four
comparison operators supported are:
- Greater than (>).
- Greater than equal to (>=).
- Less than (<).
- Less than equal to (<=).
The comparison operator is also supported by the finder methods in ActiveRecord
which internally uses where clause, for example: find_by, destroy_by,
delete_by.
The new style for comparisons has to follow advantages:
- The
whereclause with the comparison operator doesn't raise an exception whenActiveRecord::Relationuses ambiguous column name. - The
whereclause with the comparison operator handle proper precision of the database columns.
Before Rails 6.1, to add a condition with comparison in where clause, we had to add raw SQL notation.
Rails 6.0.0
>> Post.where("DATE(published_at) > DATE(?)", Date.today)
# => <ActiveRecord::Relation [...]>
>> Post.find_by("likes < ?", 10)
# => <ActiveRecord::Relation [...]>
# Following query on execution would raise exception.
>> Post.joins(:comments).where("likes > 10")
# => ambiguous column name: id
Rails 6.1.0
>> Post.where("published_at >": Date.today)
# => <ActiveRecord::Relation [...]>
>> Post.find_by("likes <": 10)
# => <ActiveRecord::Relation [...]>
# Following query on execution would NOT raise exception.
>> Post.joins(:comments).where("likes >": 10)
# => <ActiveRecord::Relation [...]>
Check out the pull request for more details on this.

Written byAbhay Nikam
Related blogs
- 01Rails 6.1 adds invert_where methodMay 4, 2021 · Chimed Palden
- 02Rails 6.1 adds in: option to validate numeric rangesApril 14, 2021 · Akanksha Jain
- 03Rails 6.1 adds delegated_type to ActiveRecordApril 6, 2021 · Akhil Gautam
- 04Rails 6.1 adds nulls_first and nulls_last to ArelMarch 9, 2021 · Berin Larson
Follow @bigbinary on X. Check out our full blog archive.