Notable ActiveRecord Changes in Rails 6 – Part 3
ActiveRecord::Relation#extract_associated – Shorthand for Extracting Associated Record
If we want to fetch the associated records from a scoped relation, we use
#collect methods on ActiveRecord::Relation before Rails 6.
Rails 6 defines
#extract_associated method for extracting associated records from a relation. Let’s look at the below code snippet for a more clear view.
Before RAILS 6 (In Rails 5.2):
#extract_associated method narrates the objective of above(
ActiveRecord::Relation#reselect – Shorthand for
Rails 6 has added
#reselect method to ActiveRecord::Relation which functions similar to the methods
#reorder. These methods are used to change the previously given conditions to new conditions.
#reselect method allows us to change the previously selected attributes to new attributes.
Before Rails 6, we can perform similar operation with method chaining of 2 methods(
unscope(:select).select(fields)) as below.
Now in Rails 6, it is more readable by using
Support for Endless Ranges in where
Ruby 2.6 has added endless ranges
(1..) which is equivalent to explicitly specifying
Float::INFINITY at the end of the range. Support for endless ranges added in Rails 6.
Let’s look at its different behaviors in different Ruby and Rails versions when using endless ranges with where method.
Before Ruby 2.6 and RAILS 6:
As endless ranges are not defined in the previous version of ruby, it is throwing a syntax error.
Ruby 2.6 and RAILS 5.2:
Endless ranges are defined in Ruby 2.6, so it is not throwing error but returning a wrong result as it is not supported by Rails 5.2 (in previous versions of Rails).
Ruby 2.6 and RAILS 6
In this Ruby and Rails versions, we have a correct result for using endless ranges with where method.
We have the only end of the range
(1..) is available. The reverse of the same i.e.,
(..1) throws syntax error so there’s no need to add support for implicit –
Allow Strong Params in ActiveRecord::Base#exists?
This commit in Rails 6 allows
ActionController::Params as argument to
ActiveRecord::Base#exists?. This works already for
Let’s look at the example
Before Rails 6:
I hope you have enjoyed this series of Rails 6 ActiveRecord methods.
Have a happy coding!!
Consulting is free – let us help you grow!
Choose Your Language
Subscribe to Our Newsletter
- Digital Marketing
- IT Consulting
- Project Management