We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
Rails 6.1 adds support to
comparison operator in the
where
clause. The four
comparison operators supported are:
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:
where
clause with the comparison operator
doesn't raise an exception when
ActiveRecord::Relation
uses ambiguous
column name.where
clause 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.
1>> Post.where("DATE(published_at) > DATE(?)", Date.today)
2# => <ActiveRecord::Relation [...]>
3
4>> Post.find_by("likes < ?", 10)
5# => <ActiveRecord::Relation [...]>
6
7# Following query on execution would raise exception.
8>> Post.joins(:comments).where("likes > 10")
9# => ambiguous column name: id
1>> Post.where("published_at >": Date.today)
2# => <ActiveRecord::Relation [...]>
3
4>> Post.find_by("likes <": 10)
5# => <ActiveRecord::Relation [...]>
6
7# Following query on execution would NOT raise exception.
8>> Post.joins(:comments).where("likes >": 10)
9# => <ActiveRecord::Relation [...]>
Check out the pull request for more details on this.