1. Upgrading to Rails 7.1
If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 7.0 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 7.1. A list of things to watch out for when upgrading is available in the Upgrading Ruby on Rails guide.
2. Major Features
2.1. Generate Dockerfiles for new Rails applications
Default Docker support to new Rails applications. When generating a new application, Rails will now include Docker-related files in the application.
These files serve as a foundational setup for deploying your Rails application in a production environment using Docker. It's important to note that these files are not meant for development purposes.
Here's a quick example of how to build and run your Rails app using these Docker files:
$ docker build -t app .
$ docker volume create app-storage
$ docker run --rm -it -v app-storage:/rails/storage -p 3000:3000 --env RAILS_MASTER_KEY=<your-config-master-key> app
You can also start a console or runner from this Docker image:
$ docker run --rm -it -v app-storage:/rails/storage --env RAILS_MASTER_KEY=<your-config-master-key> app console
For those looking to create a multi-platform image (e.g., Apple Silicon for AMD or Intel deployment), and push it to Docker Hub, follow these steps:
$ docker login -u <your-user>
$ docker buildx create --use
$ docker buildx build --push --platform=linux/amd64,linux/arm64 -t <your-user/image-name> .
This enhancement simplifies the deployment process, providing a convenient starting point for getting your Rails application up and running in a production environment.
2.2. Add ActiveRecord::Base.normalizes
ActiveRecord::Base.normalizes
declares an attribute normalization. The
normalization is applied when the attribute is assigned or updated, and the
normalized value will be persisted to the database. The normalization is also
applied to the corresponding keyword argument of query methods, allowing records
to be queried using unnormalized values.
For example:
class User < ActiveRecord::Base
normalizes :email, with: -> email { email.strip.downcase }
normalizes :phone, with: -> phone { phone.delete("^0-9").delete_prefix("1") }
end
user = User.create(email: " CRUISE-CONTROL@EXAMPLE.COM\n")
user.email # => "cruise-control@example.com"
user = User.find_by(email: "\tCRUISE-CONTROL@EXAMPLE.COM ")
user.email # => "cruise-control@example.com"
user.email_before_type_cast # => "cruise-control@example.com"
User.where(email: "\tCRUISE-CONTROL@EXAMPLE.COM ").count # => 1
User.where(["email = ?", "\tCRUISE-CONTROL@EXAMPLE.COM "]).count # => 0
User.exists?(email: "\tCRUISE-CONTROL@EXAMPLE.COM ") # => true
User.exists?(["email = ?", "\tCRUISE-CONTROL@EXAMPLE.COM "]) # => false
User.normalize_value_for(:phone, "+1 (555) 867-5309") # => "5558675309"
2.3. Add ActiveRecord::Base.generates_token_for
ActiveRecord::Base.generates_token_for
defines the generation of tokens
for a specific purpose. Generated tokens can expire and can also embed record
data. When using a token to fetch a record, the data from the token and the
current data from the record will be compared. If the two do not match, the
token will be treated as invalid, the same as if it had expired.
Here is an example implementing a single-use password reset token:
class User < ActiveRecord::Base
has_secure_password
generates_token_for :password_reset, expires_in: 15.minutes do
# `password_salt` (defined by `has_secure_password`) returns the salt for
# the password. The salt changes when the password is changed, so the token
# will expire when the password is changed.
password_salt&.last(10)
end
end
user = User.first
token = user.generate_token_for(:password_reset)
User.find_by_token_for(:password_reset, token) # => user
user.update!(password: "new password")
User.find_by_token_for(:password_reset, token) # => nil
2.4. Add perform_all_later
to enqueue multiple jobs at once
The perform_all_later
method in Active Job,
designed to streamline the process of enqueuing multiple jobs simultaneously. This powerful
addition allows you to efficiently enqueue jobs without triggering callbacks. This is
particularly useful when you need to enqueue a batch of jobs at once, reducing the overhead
of multiple round-trips to the queue datastore.
Here's how you can take advantage of perform_all_later
:
# Enqueueing individual jobs
ActiveJob.perform_all_later(MyJob.new("hello", 42), MyJob.new("world", 0))
# Enqueueing an array of jobs
user_jobs = User.pluck(:id).map { |id| UserJob.new(user_id: id) }
ActiveJob.perform_all_later(user_jobs)
By utilizing perform_all_later
, you can optimize your job enqueuing process and take advantage
of improved efficiency, especially when working with large sets of jobs. It's worth noting that
for queue adapters that support the new enqueue_all
method, such as the Sidekiq adapter, the
enqueuing process is further optimized using push_bulk
.
Please be aware that this new method introduces a separate event, enqueue_all.active_job
,
and does not utilize the existing enqueue.active_job
event. This ensures accurate tracking
and reporting of the bulk enqueuing process.
2.5. Composite primary keys
Composite primary keys are now supported at both the database and application level. Rails is able to derive these keys directly from the schema. This feature is particularly beneficial for many-to-many relationships and other complex data models where a single column is insufficient to uniquely identify a record.
The SQL generated by query methods in Active Record (e.g. #reload
, #update
, #delete
) will contain all parts of the composite primary key. Methods like #first
and #last
will use the full composite primary key in the ORDER BY
statements.
The query_constraints
macro can be used as a "virtual primary key" to achieve the same behavior without modifying the database schema.
Example:
class TravelRoute < ActiveRecord::Base
query_constraints :origin, :destination
end
Similarly, associations accept a query_constraints:
option. This option serves as a composite foreign key, configuring the list of columns used for accessing the associated record.
Example:
class TravelRouteReview < ActiveRecord::Base
belongs_to :travel_route, query_constraints: [:travel_route_origin, :travel_route_destination]
end
2.6. Introduce adapter for Trilogy
A new adapter has been introduced to facilitate the
seamless integration of Trilogy
, a MySQL-compatible database client, with Rails applications.
Now, Rails applications have the option to incorporate Trilogy
functionality by configuring their
config/database.yml
file. For instance:
development:
adapter: trilogy
database: blog_development
pool: 5
Alternatively, integration can be achieved using the DATABASE_URL
environment variable:
ENV["DATABASE_URL"] # => "trilogy://localhost/blog_development?pool=5"
2.7. Add ActiveSupport::MessagePack
ActiveSupport::MessagePack
is a serializer that integrates with the
msgpack
gem. ActiveSupport::MessagePack
can serialize the basic Ruby
types supported by msgpack
, as well as several additional types such as Time
,
ActiveSupport::TimeWithZone
, and ActiveSupport::HashWithIndifferentAccess
.
Compared to JSON
and Marshal
, ActiveSupport::MessagePack
can reduce
payload size and improve performance.
ActiveSupport::MessagePack
can be used as a message serializer:
config.active_support.message_serializer = :message_pack
# Or individually:
ActiveSupport::MessageEncryptor.new(secret, serializer: :message_pack)
ActiveSupport::MessageVerifier.new(secret, serializer: :message_pack)
As the cookies serializer:
config.action_dispatch.cookies_serializer = :message_pack
And as a cache serializer:
config.cache_store = :file_store, "tmp/cache", { serializer: :message_pack }
# Or individually:
ActiveSupport::Cache.lookup_store(:file_store, "tmp/cache", serializer: :message_pack)
2.8. Introducing config.autoload_lib
and config.autoload_lib_once
for Enhanced Autoloading
A new configuration method, config.autoload_lib(ignore:)
,
has been introduced. This method is used to enhance the autoload paths of applications by including the
lib
directory, which is not included by default. Also, config.autoload_lib(ignore: %w(assets tasks))
is generated for new applications.
When invoked from either config/application.rb
or config/environments/*.rb
, this method adds the
lib
directory to both config.autoload_paths
and config.eager_load_paths
. It's important to note
that this feature is not available for engines.
To ensure flexibility, the ignore
keyword argument can be used to specify subdirectories within the
lib
directory that should not be managed by the autoloaders. For instance, you can exclude directories
like assets
, tasks
, and generators
by passing them to the ignore
argument:
config.autoload_lib(ignore: %w(assets tasks generators))
The config.autoload_lib_once
method is similar to
config.autoload_lib
, except that it adds lib
to config.autoload_once_paths
instead.
Please, see more details in the autoloading guide
2.9. Active Record API for general async queries
A significant enhancement has been introduced to the Active Record API, expanding its
support for asynchronous queries. This enhancement
addresses the need for more efficient handling of not-so-fast queries, particularly focusing on
aggregates (such as count
, sum
, etc.) and all methods returning a single record or anything
other than a Relation
.
The new API includes the following asynchronous methods:
async_count
async_sum
async_minimum
async_maximum
async_average
async_pluck
async_pick
async_ids
async_find_by_sql
async_count_by_sql
Here's a brief example of how to use one of these methods, async_count
, to count the number of published
posts in an asynchronous manner:
# Synchronous count
published_count = Post.where(published: true).count # => 10
# Asynchronous count
promise = Post.where(published: true).async_count # => #<ActiveRecord::Promise status=pending>
promise.value # => 10
These methods allow for the execution of these operations in an asynchronous manner, which can significantly improve performance for certain types of database queries.
2.10. Allow templates to set strict locals
Introduce a new feature that allows templates to set explicit locals
.
This enhancement provides greater control and clarity when passing variables to your templates.
By default, templates will accept any locals
as keyword arguments. However, now you can define what locals
a
template should accept by adding a locals
magic comment at the beginning of your template file.
Here's how it works:
<%# locals: (message:) -%>
<%= message %>
You can also set default values for these locals:
<%# locals: (message: "Hello, world!") -%>
<%= message %>
Optional keyword arguments can be splatted:
<%# locals: (message: "Hello, world!", **attributes) -%>
<%= tag.p(message, **attributes) %>
If you want to disable the use of locals entirely, you can do so like this:
<%# locals: () %>
Action View will process the locals:
magic comment in any templating engine that supports #
-prefixed comments, and will read the magic comment from any line in the partial.
Only keyword arguments are supported. Defining positional or block arguments will raise an Action View Error at render-time.
2.11. Add Rails.application.deprecators
The new Rails.application.deprecators
method returns a
collection of managed deprecators within your application, and allows you to add and retrieve individual
deprecators with ease:
Rails.application.deprecators[:my_gem] = ActiveSupport::Deprecation.new("2.0", "MyGem")
Rails.application.deprecators[:other_gem] = ActiveSupport::Deprecation.new("3.0", "OtherGem")
The collection's configuration settings affect all deprecators in the collection.
Rails.application.deprecators.debug = true
Rails.application.deprecators[:my_gem].debug
# => true
Rails.application.deprecators[:other_gem].debug
# => true
There are scenarios where you might want to mute all deprecator warnings for a specific block of code. With the deprecators collection, you can easily silence all deprecator warnings within a block:
Rails.application.deprecators.silence do
Rails.application.deprecators[:my_gem].warn # No warning (silenced)
Rails.application.deprecators[:other_gem].warn # No warning (silenced)
end
2.12. Support pattern matching for JSON response.parsed_body
When ActionDispatch::IntegrationTest
tests blocks invoke
response.parsed_body
for JSON responses, their payloads will be available with
indifferent access. This enables integration with Ruby's Pattern
Matching, and built-in Minitest support for pattern
matching:
get "/posts.json"
response.content_type # => "application/json; charset=utf-8"
response.parsed_body.class # => Array
response.parsed_body # => [{"id"=>42, "title"=>"Title"},...
assert_pattern { response.parsed_body => [{ id: 42 }] }
get "/posts/42.json"
response.content_type # => "application/json; charset=utf-8"
response.parsed_body.class # => ActiveSupport::HashWithIndifferentAccess
response.parsed_body # => {"id"=>42, "title"=>"Title"}
assert_pattern { response.parsed_body => [{ title: /title/i }] }
2.13. Extend response.parsed_body
to parse HTML with Nokogiri
Extend the ActionDispatch::Testing
module to support parsing the
value of an HTML response.body
into a Nokogiri::HTML5::Document
instance:
get "/posts"
response.content_type # => "text/html; charset=utf-8"
response.parsed_body.class # => Nokogiri::HTML5::Document
response.parsed_body.to_html # => "<!DOCTYPE html>\n<html>\n..."
Newly added Nokogiri support for pattern matching, along with built-in Minitest support for pattern matching presents opportunities to make test assertions about the structure and content of the HTML response:
get "/posts"
html = response.parsed_body # => <html>
# <head></head>
# <body>
# <main><h1>Some main content</h1></main>
# </body>
# </html>
assert_pattern { html.at("main") => { content: "Some main content" } }
assert_pattern { html.at("main") => { content: /content/ } }
assert_pattern { html.at("main") => { children: [{ name: "h1", content: /content/ }] } }