Notable ActiveRecord changes in Rails 6 – Part 1
In this article, we will look into some new ActiveRecord methods introduced in Rails 6. This version of Rails requires Ruby version 2.5.0 or higher.
ActiveRecord::Relation#pick – Shorthand for Single Value Plucks
Lets’ first recall #pluck method, that is since rails version 3.2.0. #pluck method is a shortcut for selecting one or more attributes without loading a bunch of records.
But to get just single value(s), we do something like this.
Before RAILS 6:
From Rails 6.0, we can use the method #pick method, which is shorthand for
create_or_find_by! – Methods added to Rails 6. Both rely on unique constraints on the underlying table. It is used to create a new record in the database with given data that has one or more unique constraints of its columns. If a record already exists with unique constraints, it raises an exception which is the same as raised in insertion and finds the existing record with given attributes using
Add negative scopes to all enum values
Rails enum has been very popular among Rails developers especially for generated named scope. So far there to get negative scope we need to use where.not with a positive scope which now supported by
not_* scopes generated by
It is convenient when we want to disallow access in a controller, like
Implicit order column is now configurable
By default ActiveRecord sorts records by primary key, so when calling ordered finder methods such as #first or #last without an explicit order clause. It may result in unpredictable and surprising behavior when the primary key is not an auto-incrementing integer, for example when it’s UUID.
This change makes it possible to override the column used for implicit ordering such that it will return more predictable results when calling first and last methods.
I hope this post helped you to start using new Rails 6 features. I would recommend checking out couple of more ActiveRecord methods added in Rails 6 in Part 2. and Part 3. Have a happy coding!
At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
Subscribe to Our Newsletter
- Digital Marketing
- IT Consulting
- Project Management