A summary of data about the Ruby ecosystem.

Recent Releases of https://github.com/rails/rails

https://github.com/rails/rails - 7.0.2.2

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix Reloader method signature to work with the new Executor signature

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 7.0.2.1

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Under certain circumstances, the middleware isn't informed that the
    response body has been fully closed which result in request state not
    being fully reset before the next request

    [CVE-2022-23633]

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.1.4.6

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix Reloader method signature to work with the new Executor signature

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.1.4.5

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Under certain circumstances, the middleware isn't informed that the
    response body has been fully closed which result in request state not
    being fully reset before the next request

    [CVE-2022-23633]

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.0.4.6

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix Reloader method signature to work with the new Executor signature

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.0.4.5

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Under certain circumstances, the middleware isn't informed that the
    response body has been fully closed which result in request state not
    being fully reset before the next request

    [CVE-2022-23633]

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 5.2.6.2

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix Reloader method signature to work with the new Executor signature

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 5.2.6.1

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Under certain circumstances, the middleware isn't informed that the
    response body has been fully closed which result in request state not
    being fully reset before the next request

    [CVE-2022-23633]

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 7.0.2

Active Support

  • Fix ActiveSupport::EncryptedConfiguration to be compatible with Psych 4

    Stephen Sugden

  • Improve File.atomic_write error handling.

    Daniel Pepper

Active Model

  • Use different cache namespace for proxy calls

    Models can currently have different attribute bodies for the same method
    names, leading to conflicts. Adding a new namespace :active_model_proxy
    fixes the issue.

    Chris Salzberg

Active Record

  • Fix PG.connect keyword arguments deprecation warning on ruby 2.7.

    Nikita Vasilevsky

  • Fix the ability to exclude encryption params from being autofiltered.

    Mark Gangl

  • Dump the precision for datetime columns following the new defaults.

    Rafael Mendonça França

  • Make sure encrypted attributes are not being filtered twice.

    Nikita Vasilevsky

  • Dump the database schema containing the current Rails version.

    Since https://github.com/rails/rails/pull/42297, Rails now generate datetime columns
    with a default precision of 6. This means that users upgrading to Rails 7.0 from 6.1,
    when loading the database schema, would get the new precision value, which would not match
    the production schema.

    To avoid this the schema dumper will generate the new format which will include the Rails
    version and will look like this:

    ActiveRecord::Schema[7.0].define
    

    When upgrading from Rails 6.1 to Rails 7.0, you can run the rails app:update task that will
    set the current schema version to 6.1.

    Rafael Mendonça França

  • Fix parsing expression for PostgreSQL generated column.

    fatkodima

  • Fix Mysql2::Error: Commands out of sync; you can't run this command now
    when bulk-inserting fixtures that exceed max_allowed_packet configuration.

    Nikita Vasilevsky

  • Fix error when saving an association with a relation named record.

    Dorian Marié

  • Fix MySQL::SchemaDumper behavior about datetime precision value.

    y0t4

  • Improve associated with no reflection error.

    Nikolai

  • Fix PG.connect keyword arguments deprecation warning on ruby 2.7.

    Fixes #44307.

    Nikita Vasilevsky

  • Fix passing options to check_constraint from change_table.

    Frederick Cheung

Action View

  • Ensure preload_link_tag preloads JavaScript modules correctly.

    Máximo Mussini

  • Fix stylesheet_link_tag and similar helpers are being used to work in objects with
    a response method.

    dark-panda

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • Revert the ability to pass service_name param to DirectUploadsController which was introduced
    in 7.0.0.

    That change caused a lot of problems to upgrade Rails applications so we decided to remove it
    while in work in a more backwards compatible implementation.

    Gannon McGibbon

  • Allow applications to opt out of precompiling Active Storage JavaScript assets.

    jlestavel

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 7.0.1

Active Support

Active Model

  • No changes.

Active Record

  • Change QueryMethods#in_order_of to drop records not listed in values.

    in_order_of now filters down to the values provided, to match the behavior of the Enumerable version.

    Kevin Newton

  • Allow named expression indexes to be revertible.

    Previously, the following code would raise an error in a reversible migration executed while rolling back, due to the index name not being used in the index removal.

    add_index(:settings, "(data->'property')", using: :gin, name: :index_settings_data_property)
    

    Fixes #43331.

    Oliver Günther

  • Better error messages when association name is invalid in the argument of ActiveRecord::QueryMethods::WhereChain#missing.

    ykpythemind

  • Fix ordered migrations for single db in multi db environment.

    Himanshu

  • Extract on update CURRENT_TIMESTAMP for mysql2 adapter.

    Kazuhiro Masuda

  • Fix incorrect argument in PostgreSQL structure dump tasks.

    Updating the --no-comment argument added in Rails 7 to the correct --no-comments argument.

    Alex Dent

  • Fix schema dumping column default SQL values for sqlite3.

    fatkodima

  • Correctly parse complex check constraint expressions for PostgreSQL.

    fatkodima

  • Fix timestamptz attributes on PostgreSQL handle blank inputs.

    Alex Ghiculescu

  • Fix migration compatibility to create SQLite references/belongs_to column as integer when migration version is 6.0.

    Reference/belongs_to in migrations with version 6.0 were creating columns as
    bigint instead of integer for the SQLite Adapter.

    Marcelo Lauxen

  • Fix joining through a polymorphic association.

    Alexandre Ruban

  • Fix QueryMethods#in_order_of to handle empty order list.

    Post.in_order_of(:id, []).to_a
    

    Also more explicitly set the column as secondary order, so that any other
    value is still ordered.

    Jean Boussier

  • Fix rails dbconsole for 3-tier config.

    Eileen M. Uchitelle

  • Fix quoting of column aliases generated by calculation methods.

    Since the alias is derived from the table name, we can't assume the result
    is a valid identifier.

    class Test < ActiveRecord::Base
      self.table_name = '1abc'
    end
    Test.group(:id).count
    # syntax error at or near "1" (ActiveRecord::StatementInvalid)
    # LINE 1: SELECT COUNT(*) AS count_all, "1abc"."id" AS 1abc_id FROM "1...
    

    Jean Boussier

Action View

  • Fix button_to to work with a hash parameter as URL.

    MingyuanQin

  • Fix link_to with a model passed as an argument twice.

    Alex Ghiculescu

Action Pack

  • Fix ActionController::Parameters methods to keep the original logger context when creating a new copy
    of the original object.

    Yutaka Kamei

Active Job

  • Allow testing discard_on/retry_on ActiveJob::DeserializationError

    Previously in perform_enqueued_jobs, deserialize_arguments_if_needed
    was called before calling perform_now. When a record no longer exists
    and is serialized using GlobalID this led to raising
    an ActiveJob::DeserializationError before reaching perform_now call.
    This behaviour makes difficult testing the job discard_on/retry_on logic.

    Now deserialize_arguments_if_needed call is postponed to when perform_now
    is called.

    Example:

    class UpdateUserJob < ActiveJob::Base
      discard_on ActiveJob::DeserializationError
    
      def perform(user)
        # ...
      end
    end
    
    # In the test
    User.destroy_all
    assert_nothing_raised do
      perform_enqueued_jobs only: UpdateUserJob
    end
    

    Jacopo Beschi

Action Mailer

  • Keep configuration of smtp_settings consistent between 6.1 and 7.0.

    André Luis Leal Cardoso Junior

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • Prevent duplicate entries in plugin Gemfile.

    Jonathan Hefner

  • Fix asset pipeline errors for plugin dummy apps.

    Jonathan Hefner

  • Fix generated route revocation.

    Jonathan Hefner

  • Addresses an issue in which Sidekiq jobs could not reload certain
    namespaces.

    See fxn/zeitwerk#198 for
    details.

    Xavier Noria

  • Fix plugin generator to a plugin that pass all the tests.

    Rafael Mendonça França

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 7.0.0

Action Cable

  • The Action Cable client now ensures successful channel subscriptions:

    • The client maintains a set of pending subscriptions until either
      the server confirms the subscription or the channel is torn down.
    • Rectifies the race condition where an unsubscribe is rapidly followed
      by a subscribe (on the same channel identifier) and the requests are
      handled out of order by the ActionCable server, thereby ignoring the
      subscribe command.

    Daniel Spinosa

  • Compile ESM package that can be used directly in the browser as actioncable.esm.js.

    DHH

  • Move action_cable.js to actioncable.js to match naming convention used for other Rails frameworks, and use JS console to communicate the deprecation.

    DHH

  • Stop transpiling the UMD package generated as actioncable.js and drop the IE11 testing that relied on that.

    DHH

  • Truncate broadcast logging messages.

    J Smith

  • OpenSSL constants are now used for Digest computations.

    Dirkjan Bussink

  • The Action Cable client now includes safeguards to prevent a "thundering
    herd" of client reconnects after server connectivity loss:

    • The client will wait a random amount between 1x and 3x of the stale
      threshold after the server's last ping before making the first
      reconnection attempt.
    • Subsequent reconnection attempts now use exponential backoff instead of
      logarithmic backoff. To allow the delay between reconnection attempts to
      increase slowly at first, the default exponentiation base is < 2.
    • Random jitter is applied to each delay between reconnection attempts.

    Jonathan Hefner

Action Mailbox

  • Removed deprecated environment variable MAILGUN_INGRESS_API_KEY.

    Rafael Mendonça França

  • Removed deprecated Rails.application.credentials.action_mailbox.mailgun_api_key.

    Rafael Mendonça França

  • Add attachments to the list of permitted parameters for inbound emails conductor.

    When using the conductor to test inbound emails with attachments, this prevents an
    unpermitted parameter warning in default configurations, and prevents errors for
    applications that set:

    config.action_controller.action_on_unpermitted_parameters = :raise
    

    David Jones, Dana Henke

  • Add ability to configure ActiveStorage service
    for storing email raw source.

    # config/storage.yml
    incoming_emails:
      service: Disk
      root: /secure/dir/for/emails/only
    
    config.action_mailbox.storage_service = :incoming_emails
    

    Yurii Rashkovskii

  • Add ability to incinerate an inbound message through the conductor interface.

    Santiago Bartesaghi

  • OpenSSL constants are now used for Digest computations.

    Dirkjan Bussink

Action Mailer

  • Remove deprecated ActionMailer::DeliveryJob and ActionMailer::Parameterized::DeliveryJob
    in favor of ActionMailer::MailDeliveryJob.

    Rafael Mendonça França

  • email_address_with_name returns just the address if name is blank.

    Thomas Hutterer

  • Configures a default of 5 for both open_timeout and read_timeout for SMTP Settings.

    André Luis Leal Cardoso Junior

Action Pack

  • Deprecate Rails.application.config.action_controller.urlsafe_csrf_tokens. This config is now always enabled.

    Étienne Barrié

  • Instance variables set in requests in a ActionController::TestCase are now cleared before the next request

    This means if you make multiple requests in the same test, instance variables set in the first request will
    not persist into the second one. (It's not recommended to make multiple requests in the same test.)

    Alex Ghiculescu

  • Rails.application.executor hooks can now be called around every request in a ActionController::TestCase

    This helps to better simulate request or job local state being reset between requests and prevent state
    leaking from one request to another.

    To enable this, set config.active_support.executor_around_test_case = true (this is the default in Rails 7).

    Alex Ghiculescu

  • Consider onion services secure for cookies.

    Justin Tracey

  • Remove deprecated Rails.config.action_view.raise_on_missing_translations.

    Rafael Mendonça França

  • Remove deprecated support to passing a path to fixture_file_upload relative to fixture_path.

    Rafael Mendonça França

  • Remove deprecated ActionDispatch::SystemTestCase#host!.

    Rafael Mendonça França

  • Remove deprecated Rails.config.action_dispatch.hosts_response_app.

    Rafael Mendonça França

  • Remove deprecated ActionDispatch::Response.return_only_media_type_on_content_type.

    Rafael Mendonça França

  • Raise ActionController::Redirecting::UnsafeRedirectError for unsafe redirect_to redirects.

    This allows rescue_from to be used to add a default fallback route:

    rescue_from ActionController::Redirecting::UnsafeRedirectError do
      redirect_to root_url
    end
    

    Kasper Timm Hansen, Chris Oliver

  • Add url_from to verify a redirect location is internal.

    Takes the open redirect protection from redirect_to so users can wrap a
    param, and fall back to an alternate redirect URL when the param provided
    one is unsafe.

    def create
      redirect_to url_from(params[:redirect_url]) || root_url
    end
    

    dmcge, Kasper Timm Hansen

  • Allow Capybara driver name overrides in SystemTestCase::driven_by

    Allow users to prevent conflicts among drivers that use the same driver
    type (selenium, poltergeist, webkit, rack test).

    Fixes #42502

    Chris LaRose

  • Allow multiline to be passed in routes when using wildcard segments.

    Previously routes with newlines weren't detected when using wildcard segments, returning
    a No route matches error.
    After this change, routes with newlines are detected on wildcard segments. Example

      draw do
        get "/wildcard/*wildcard_segment", to: SimpleApp.new("foo#index"), as: :wildcard
      end
    
      # After the change, the path matches.
      assert_equal "/wildcard/a%0Anewline", url_helpers.wildcard_path(wildcard_segment: "a\nnewline")
    

    Fixes #39103

    Ignacio Chiazzo

  • Treat html suffix in controller translation.

    Rui Onodera, Gavin Miller

  • Allow permitting numeric params.

    Previously it was impossible to permit different fields on numeric parameters.
    After this change you can specify different fields for each numbered parameter.
    For example params like,

    book: {
            authors_attributes: {
              '0': { name: "William Shakespeare", age_of_death: "52" },
              '1': { name: "Unattributed Assistant" },
              '2': "Not a hash",
              'new_record': { name: "Some name" }
            }
          }
    

    Before you could permit name on each author with,
    permit book: { authors_attributes: [ :name ] }

    After this change you can permit different keys on each numbered element,
    permit book: { authors_attributes: { '1': [ :name ], '0': [ :name, :age_of_death ] } }

    Fixes #41625

    Adam Hess

  • Update HostAuthorization middleware to render debug info only
    when config.consider_all_requests_local is set to true.

    Also, blocked host info is always logged with level error.

    Fixes #42813

    Nikita Vyrko

  • Add Server-Timing middleware

    Server-Timing specification defines how the server can communicate to browsers performance metrics
    about the request it is responding to.

    The ServerTiming middleware is enabled by default on development environment by default using the
    config.server_timing setting and set the relevant duration metrics in the Server-Timing header

    The full specification for Server-Timing header can be found in: https://www.w3.org/TR/server-timing/#dfn-server-timing-header-field

    Sebastian Sogamoso, Guillermo Iguaran

  • Use a static error message when raising ActionDispatch::Http::Parameters::ParseError
    to avoid inadvertently logging the HTTP request body at the fatal level when it contains
    malformed JSON.

    Fixes #41145

    Aaron Lahey

  • Add Middleware#delete! to delete middleware or raise if not found.

    Middleware#delete! works just like Middleware#delete but will
    raise an error if the middleware isn't found.

    Alex Ghiculescu, Petrik de Heus, Junichi Sato

  • Raise error on unpermitted open redirects.

    Add allow_other_host options to redirect_to.
    Opt in to this behaviour with ActionController::Base.raise_on_open_redirects = true.

    Gannon McGibbon

  • Deprecate poltergeist and webkit (capybara-webkit) driver registration for system testing (they will be removed in Rails 7.1). Add cuprite instead.

    Poltergeist and capybara-webkit are already not maintained. These usage in Rails are removed for avoiding confusing users.

    Cuprite is a good alternative to Poltergeist. Some guide descriptions are replaced from Poltergeist to Cuprite.

    Yusuke Iwaki

  • Exclude additional flash types from ActionController::Base.action_methods.

    Ensures that additional flash types defined on ActionController::Base subclasses
    are not listed as actions on that controller.

    class MyController < ApplicationController
      add_flash_types :hype
    end
    
    MyController.action_methods.include?('hype') # => false
    

    Gavin Morrice

  • OpenSSL constants are now used for Digest computations.

    Dirkjan Bussink

  • Remove IE6-7-8 file download related hack/fix from ActionController::DataStreaming module.

    Due to the age of those versions of IE this fix is no longer relevant, more importantly it creates an edge-case for unexpected Cache-Control headers.

    Tadas Sasnauskas

  • Configuration setting to skip logging an uncaught exception backtrace when the exception is
    present in rescued_responses.

    It may be too noisy to get all backtraces logged for applications that manage uncaught
    exceptions via rescued_responses and exceptions_app.
    config.action_dispatch.log_rescued_responses (defaults to true) can be set to false in
    this case, so that only exceptions not found in rescued_responses will be logged.

    Alexander Azarov, Mike Dalessio

  • Ignore file fixtures on db:fixtures:load.

    Kevin Sjöberg

  • Fix ActionController::Live controller test deadlocks by removing the body buffer size limit for tests.

    Dylan Thacker-Smith

  • New ActionController::ConditionalGet#no_store method to set HTTP cache control no-store directive.

    Tadas Sasnauskas

  • Drop support for the SERVER_ADDR header.

    Following up https://github.com/rack/rack/pull/1573 and https://github.com/rails/rails/pull/42349.

    Ricardo Díaz

  • Set session options when initializing a basic session.

    Gannon McGibbon

  • Add cache_control: {} option to fresh_when and stale?.

    Works as a shortcut to set response.cache_control with the above methods.

    Jacopo Beschi

  • Writing into a disabled session will now raise an error.

    Previously when no session store was set, writing into the session would silently fail.

    Jean Boussier

  • Add support for 'require-trusted-types-for' and 'trusted-types' headers.

    Fixes #42034.

    lfalcao

  • Remove inline styles and address basic accessibility issues on rescue templates.

    Jacob Herrington

  • Add support for 'private, no-store' Cache-Control headers.

    Previously, 'no-store' was exclusive; no other directives could be specified.

    Alex Smith

  • Expand payload of unpermitted_parameters.action_controller instrumentation to allow subscribers to
    know which controller action received unpermitted parameters.

    bbuchalter

  • Add ActionController::Live#send_stream that makes it more convenient to send generated streams:

    send_stream(filename: "subscribers.csv") do |stream|
      stream.writeln "email_address,updated_at"
    
      @subscribers.find_each do |subscriber|
        stream.writeln [ subscriber.email_address, subscriber.updated_at ].join(",")
      end
    end
    

    DHH

  • Add ActionController::Live::Buffer#writeln to write a line to the stream with a newline included.

    DHH

  • ActionDispatch::Request#content_type now returned Content-Type header as it is.

    Previously, ActionDispatch::Request#content_type returned value does NOT contain charset part.
    This behavior changed to returned Content-Type header containing charset part as it is.

    If you want just MIME type, please use ActionDispatch::Request#media_type instead.

    Before:

    request = ActionDispatch::Request.new("CONTENT_TYPE" => "text/csv; header=present; charset=utf-16", "REQUEST_METHOD" => "GET")
    request.content_type #=> "text/csv"
    

    After:

    request = ActionDispatch::Request.new("Content-Type" => "text/csv; header=present; charset=utf-16", "REQUEST_METHOD" => "GET")
    request.content_type #=> "text/csv; header=present; charset=utf-16"
    request.media_type   #=> "text/csv"
    

    Rafael Mendonça França

  • Change ActionDispatch::Request#media_type to return nil when the request don't have a Content-Type header.

    Rafael Mendonça França

  • Fix error in ActionController::LogSubscriber that would happen when throwing inside a controller action.

    Janko Marohnić

  • Allow anything with #to_str (like Addressable::URI) as a redirect_to location.

    ojab

  • Change the request method to a GET when passing failed requests down to config.exceptions_app.

    Alex Robbin

  • Deprecate the ability to assign a single value to config.action_dispatch.trusted_proxies
    as RemoteIp middleware behaves inconsistently depending on whether this is configured
    with a single value or an enumerable.

    Fixes #40772.

    Christian Sutter

  • Add redirect_back_or_to(fallback_location, **) as a more aesthetically pleasing version of redirect_back fallback_location:, **.
    The old method name is retained without explicit deprecation.

    DHH

Action Text

  • Fix an issue with how nested lists were displayed when converting to plain text

    Matt Swanson

  • Allow passing in a custom direct_upload_url or blob_url_template to rich_text_area_tag.

    Lucas Mansur

  • Make the Action Text + Trix JavaScript and CSS available through the asset pipeline.

    DHH

  • OpenSSL constants are now used for Digest computations.

    Dirkjan Bussink

  • Add support for passing form: option to rich_text_area_tag and
    rich_text_area helpers to specify the <input type="hidden" form="...">
    value.

    Sean Doyle

  • Add config.action_text.attachment_tag_name, to specify the HTML tag that contains attachments.

    Mark VanLandingham

  • Expose how we render the HTML surrounding rich text content as an
    extensible layouts/action_view/contents/_content.html.erb template to
    encourage user-land customizations, while retaining private API control over how
    the rich text itself is rendered by action_text/contents/_content.html.erb
    partial.

    Sean Doyle

  • Add with_all_rich_text method to eager load all rich text associations on a model at once.

    Matt Swanson, DHH

Action View

  • Support include_hidden: option in calls to
    ActionView::Helper::FormBuilder#file_field with multiple: true to
    support submitting an empty collection of files.

    form.file_field :attachments, multiple: true
    # => <input type="hidden" autocomplete="off" name="post[attachments][]" value="">
         <input type="file" multiple="multiple" id="post_attachments" name="post[attachments][]">
    
    form.file_field :attachments, multiple: true, include_hidden: false
    # => <input type="file" multiple="multiple" id="post_attachments" name="post[attachments][]">
    

    Sean Doyle

  • Fix number_with_precision(raise: true) always raising even on valid numbers.

    Pedro Moreira

  • Support fields model: [@nested, @model] the same way as form_with model: [@nested, @model].

    Sean Doyle

  • Infer HTTP verb [method] from a model or Array with model as the first
    argument to button_to when combined with a block:

    button_to(Workshop.find(1)){ "Update" }
    #=> <form method="post" action="/workshops/1" class="button_to">
    #=>   <input type="hidden" name="_method" value="patch" autocomplete="off" />
    #=>   <button type="submit">Update</button>
    #=> </form>
    
    button_to([ Workshop.find(1), Session.find(1) ]) { "Update" }
    #=> <form method="post" action="/workshops/1/sessions/1" class="button_to">
    #=>   <input type="hidden" name="_method" value="patch" autocomplete="off" />
    #=>   <button type="submit">Update</button>
    #=> </form>
    

    Sean Doyle

  • Support passing a Symbol as the first argument to FormBuilder#button:

    form.button(:draft, value: true)
    # => <button name="post[draft]" value="true" type="submit">Create post</button>
    
    form.button(:draft, value: true) do
      content_tag(:strong, "Save as draft")
    end
    # =>  <button name="post[draft]" value="true" type="submit">
    #       <strong>Save as draft</strong>
    #     </button>
    

    Sean Doyle

  • Introduce the field_name view helper, along with the
    FormBuilder#field_name counterpart:

    form_for @post do |f|
      f.field_tag :tag, name: f.field_name(:tag, multiple: true)
      # => <input type="text" name="post[tag][]">
    end
    

    Sean Doyle

  • Execute the ActionView::Base.field_error_proc within the context of the
    ActionView::Base instance:

    config.action_view.field_error_proc = proc { |html| content_tag(:div, html, class: "field_with_errors") }
    

    Sean Doyle

  • Add support for button_to ..., authenticity_token: false

    button_to "Create", Post.new, authenticity_token: false
    # => <form class="button_to" method="post" action="/posts"><button type="submit">Create</button></form>
    
    button_to "Create", Post.new, authenticity_token: true
    # => <form class="button_to" method="post" action="/posts"><button type="submit">Create</button><input type="hidden" name="form_token" value="abc123..." autocomplete="off" /></form>
    
    button_to "Create", Post.new, authenticity_token: "secret"
    # => <form class="button_to" method="post" action="/posts"><button type="submit">Create</button><input type="hidden" name="form_token" value="secret" autocomplete="off" /></form>
    

    Sean Doyle

  • Support rendering <form> elements without [action] attributes by:

    • form_with url: false or form_with ..., html: { action: false }
    • form_for ..., url: false or form_for ..., html: { action: false }
    • form_tag false or form_tag ..., action: false
    • button_to "...", false or button_to(false) { ... }

    Sean Doyle

  • Add :day_format option to date_select

    date_select("article", "written_on", day_format: ->(day) { day.ordinalize })
    # generates day options like <option value="1">1st</option>\n<option value="2">2nd</option>...
    

    Shunichi Ikegami

  • Allow link_to helper to infer link name from Model#to_s when it
    is used with a single argument:

    link_to @profile
    #=> <a href="/profiles/1">Eileen</a>
    

    This assumes the model class implements a to_s method like this:

    class Profile < ApplicationRecord
      # ...
      def to_s
        name
      end
    end
    

    Previously you had to supply a second argument even if the Profile
    model implemented a #to_s method that called the name method.

    link_to @profile, @profile.name
    #=> <a href="/profiles/1">Eileen</a>
    

    Olivier Lacan

  • Support svg unpaired tags for tag helper.

    tag.svg { tag.use('href' => "#cool-icon") }
    # => <svg><use href="#cool-icon"></svg>
    

    Oleksii Vasyliev

  • Improves the performance of ActionView::Helpers::NumberHelper formatters by avoiding the use of
    exceptions as flow control.

    Mike Dalessio

  • preload_link_tag properly inserts as attributes for files with image MIME types, such as JPG or SVG.

    Nate Berkopec

  • Add weekday_options_for_select and weekday_select helper methods. Also adds weekday_select to FormBuilder.

    Drew Bragg, Dana Kashubeck, Kasper Timm Hansen

  • Add caching? helper that returns whether the current code path is being cached and uncacheable! to denote helper methods that can't participate in fragment caching.

    Ben Toews, John Hawthorn, Kasper Timm Hansen, Joel Hawksley

  • Add include_seconds option for time_field.

    <%= form.time_field :foo, include_seconds: false %>
    # => <input value="16:22" type="time" />
    

    Default includes seconds:

    <%= form.time_field :foo %>
    # => <input value="16:22:01.440" type="time" />
    

    This allows you to take advantage of different rendering options in some browsers.

    Alex Ghiculescu

  • Improve error messages when template file does not exist at absolute filepath.

    Ted Whang

  • Add :country_code option to sms_to for consistency with phone_to.

    Jonathan Hefner

  • OpenSSL constants are now used for Digest computations.

    Dirkjan Bussink

  • The translate helper now passes default values that aren't
    translation keys through I18n.translate for interpolation.

    Jonathan Hefner

  • Adds option extname to stylesheet_link_tag to skip default
    .css extension appended to the stylesheet path.

    Before:

    stylesheet_link_tag "style.less"
    # <link href="/stylesheets/style.less.scss" rel="stylesheet">
    

    After:

    stylesheet_link_tag "style.less", extname: false, skip_pipeline: true, rel: "stylesheet/less"
    # <link href="/stylesheets/style.less" rel="stylesheet/less">
    

    Abhay Nikam

  • Deprecate render locals to be assigned to instance variables.

    Petrik de Heus

  • Remove legacy default media=screen from stylesheet_link_tag.

    André Luis Leal Cardoso Junior

  • Change ActionView::Helpers::FormBuilder#button to transform formmethod
    attributes into _method="$VERB" Form Data to enable varied same-form actions:

    <%= form_with model: post, method: :put do %>
      <%= form.button "Update" %>
      <%= form.button "Delete", formmethod: :delete %>
    <% end %>
    <%# => <form action="posts/1">
        =>   <input type="hidden" name="_method" value="put">
        =>   <button type="submit">Update</button>
        =>   <button type="submit" formmethod="post" name="_method" value="delete">Delete</button>
        => </form>
    %>
    

    Sean Doyle

  • Change ActionView::Helpers::UrlHelper#button_to to always render a
    <button> element, regardless of whether or not the content is passed as
    the first argument or as a block.

    <%= button_to "Delete", post_path(@post), method: :delete %>
    # => <form action="/posts/1"><input type="hidden" name="_method" value="delete"><button type="submit">Delete</button></form>
    
    <%= button_to post_path(@post), method: :delete do %>
      Delete
    <% end %>
    # => <form action="/posts/1"><input type="hidden" name="_method" value="delete"><button type="submit">Delete</button></form>
    

    Sean Doyle, Dusan Orlovic

  • Add config.action_view.preload_links_header to allow disabling of
    the Link header being added by default when using stylesheet_link_tag
    and javascript_include_tag.

    Andrew White

  • The translate helper now resolves default values when a nil key is
    specified, instead of always returning nil.

    Jonathan Hefner

  • Add config.action_view.image_loading to configure the default value of
    the image_tag :loading option.

    By setting config.action_view.image_loading = "lazy", an application can opt in to
    lazy loading images sitewide, without changing view code.

    Jonathan Hefner

  • ActionView::Helpers::FormBuilder#id returns the value
    of the <form> element's id attribute. With a method argument, returns
    the id attribute for a form field with that name.

    <%= form_for @post do |f| %>
      <%# ... %>
    
      <% content_for :sticky_footer do %>
        <%= form.button(form: f.id) %>
      <% end %>
    <% end %>
    

    Sean Doyle

  • ActionView::Helpers::FormBuilder#field_id returns the value generated by
    the FormBuilder for the given attribute name.

    <%= form_for @post do |f| %>
      <%= f.label :title %>
      <%= f.text_field :title, aria: { describedby: f.field_id(:title, :error) } %>
      <%= tag.span("is blank", id: f.field_id(:title, :error) %>
    <% end %>
    

    Sean Doyle

  • Add tag.attributes to transform a Hash into HTML Attributes, ready to be
    interpolated into ERB.

    <input <%= tag.attributes(type: :text, aria: { label: "Search" }) %> >
    # => <input type="text" aria-label="Search">
    

    Sean Doyle

Active Job

  • Remove deprecated :return_false_on_aborted_enqueue option.

    Rafael Mendonça França

  • Deprecated Rails.config.active_job.skip_after_callbacks_if_terminated.

    Rafael Mendonça França

  • Removed deprecated behavior that was not halting after_enqueue/after_perform callbacks when a
    previous callback was halted with throw :abort.

    Rafael Mendonça França

  • Raise an SerializationError in Serializer::ModuleSerializer
    if the module name is not present.

    Veerpal Brar

  • Allow a job to retry indefinitely

    The attempts parameter of the retry_on method now accepts the
    symbol reference :unlimited in addition to a specific number of retry
    attempts to allow a developer to specify that a job should retry
    forever until it succeeds.

    class MyJob < ActiveJob::Base
      retry_on(AlwaysRetryException, attempts: :unlimited)
    
      # the actual job code
    end
    

    Daniel Morton

  • Added possibility to check on :priority in test helper methods
    assert_enqueued_with and assert_performed_with.

    Wojciech Wnętrzak

  • OpenSSL constants are now used for Digest computations.

    Dirkjan Bussink

  • Add a Serializer for the Range class.

    This should allow things like MyJob.perform_later(range: 1..100).

  • Communicate enqueue failures to callers of perform_later.

    perform_later can now optionally take a block which will execute after
    the adapter attempts to enqueue the job. The block will receive the job
    instance as an argument even if the enqueue was not successful.
    Additionally, ActiveJob adapters now have the ability to raise an
    ActiveJob::EnqueueError which will be caught and stored in the job
    instance so code attempting to enqueue jobs can inspect any raised
    EnqueueError using the block.

    MyJob.perform_later do |job|
      unless job.successfully_enqueued?
        if job.enqueue_error&.message == "Redis was unavailable"
          # invoke some code that will retry the job after a delay
        end
      end
    end
    

    Daniel Morton

  • Don't log rescuable exceptions defined with rescue_from.

    Hu Hailin

  • Allow rescue_from to rescue all exceptions.

    Adrianna Chang, Étienne Barrié

Active Model

  • Remove support to Marshal load Rails 5.x ActiveModel::AttributeSet format.

    Rafael Mendonça França

  • Remove support to Marshal and YAML load Rails 5.x error format.

    Rafael Mendonça França

  • Remove deprecated support to use []= in ActiveModel::Errors#messages.

    Rafael Mendonça França

  • Remove deprecated support to delete errors from ActiveModel::Errors#messages.

    Rafael Mendonça França

  • Remove deprecated support to clear errors from ActiveModel::Errors#messages.

    Rafael Mendonça França

  • Remove deprecated support concat errors to ActiveModel::Errors#messages.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#to_xml.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#keys.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#values.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#slice!.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#to_h.

    Rafael Mendonça França

  • Remove deprecated enumeration of ActiveModel::Errors instances as a Hash.

    Rafael Mendonça França

  • Clear secure password cache if password is set to nil

    Before:

    user.password = 'something'
    user.password = nil

    user.password # => 'something'

    Now:

    user.password = 'something'
    user.password = nil

    user.password # => nil

    Markus Doits

  • Introduce ActiveModel::API.

    Make ActiveModel::API the minimum API to talk with Action Pack and Action View.
    This will allow adding more functionality to ActiveModel::Model.

    Petrik de Heus, Nathaniel Watts

  • Fix dirty check for Float::NaN and BigDecimal::NaN.

    Float::NaN and BigDecimal::NaN in Ruby are special values
    and can't be compared with ==.

    Marcelo Lauxen

  • Fix to_json for ActiveModel::Dirty object.

    Exclude mutations_from_database attribute from json as it lead to recursion.

    Anil Maurya

  • Add ActiveModel::AttributeSet#values_for_database.

    Returns attributes with values for assignment to the database.

    Chris Salzberg

  • Fix delegation in ActiveModel::Type::Registry#lookup and ActiveModel::Type.lookup.

    Passing a last positional argument {} would be incorrectly considered as keyword argument.

    Benoit Daloze

  • Cache and re-use generated attribute methods.

    Generated methods with identical implementations will now share their instruction sequences
    leading to reduced memory retention, and slightly faster load time.

    Jean Boussier

  • Add in: range parameter to numericality validator.

    Michal Papis

  • Add locale argument to ActiveModel::Name#initialize to be used to generate the singular,
    plural, route_key and singular_route_key values.

    Lukas Pokorny

  • Make ActiveModel::Errors#inspect slimmer for readability

    lulalala

Active Record

  • Better handle SQL queries with invalid encoding.

    Post.create(name: "broken \xC8 UTF-8")
    

    Would cause all adapters to fail in a non controlled way in the code
    responsible to detect write queries.

    The query is now properly passed to the database connection, which might or might
    not be able to handle it, but will either succeed or failed in a more correct way.

    Jean Boussier

  • Move database and shard selection config options to a generator.

    Rather than generating the config options in production.rb when applications are created, applications can now run a generator to create an initializer and uncomment / update options as needed. All multi-db configuration can be implemented in this initializer.

    Eileen M. Uchitelle

  • Remove deprecated ActiveRecord::DatabaseConfigurations::DatabaseConfig#spec_name.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Connection#in_clause_length.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Connection#allowed_index_name_length.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base#remove_connection.

    Rafael Mendonça França

  • Load STI Models in fixtures

    Data from Fixtures now loads based on the specific class for models with
    Single Table Inheritance. This affects enums defined in subclasses, previously
    the value of these fields was not parsed and remained nil

    Andres Howard

  • #authenticate returns false when the password is blank instead of raising an error.

    Muhammad Muhammad Ibrahim

  • Fix ActiveRecord::QueryMethods#in_order_of behavior for integer enums.

    ActiveRecord::QueryMethods#in_order_of didn't work as expected for enums stored as integers in the database when passing an array of strings or symbols as the order argument. This unexpected behavior occurred because the string or symbol values were not casted to match the integers in the database.

    The following example now works as expected:

    class Book < ApplicationRecord
      enum status: [:proposed, :written, :published]
    end
    
    Book.in_order_of(:status, %w[written published proposed])
    

    Alexandre Ruban

  • Ignore persisted in-memory records when merging target lists.

    Kevin Sjöberg

  • Add a new option :update_only to upsert_all to configure the list of columns to update in case of conflict.

    Before, you could only customize the update SQL sentence via :on_duplicate. There is now a new option :update_only that lets you provide a list of columns to update in case of conflict:

    Commodity.upsert_all(
      [
        { id: 2, name: "Copper", price: 4.84 },
        { id: 4, name: "Gold", price: 1380.87 },
        { id: 6, name: "Aluminium", price: 0.35 }
      ],
      update_only: [:price] # Only prices will be updated
    )
    

    Jorge Manrubia

  • Remove deprecated ActiveRecord::Result#map! and ActiveRecord::Result#collect!.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.configurations.to_h.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.configurations.default_hash.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.arel_attribute.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.connection_config.

    Rafael Mendonça França

  • Filter attributes in SQL logs

    Previously, SQL queries in logs containing ActiveRecord::Base.filter_attributes were not filtered.

    Now, the filter attributes will be masked [FILTERED] in the logs when prepared_statement is enabled.

    # Before:
      Foo Load (0.2ms)  SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ?  [["passw", "hello"], ["LIMIT", 1]]
    
    # After:
      Foo Load (0.5ms)  SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ?  [["passw", "[FILTERED]"], ["LIMIT", 1]]
    

    Aishwarya Subramanian

  • Remove deprecated Tasks::DatabaseTasks.spec.

    Rafael Mendonça França

  • Remove deprecated Tasks::DatabaseTasks.current_config.

    Rafael Mendonça França

  • Deprecate Tasks::DatabaseTasks.schema_file_type.

    Rafael Mendonça França

  • Remove deprecated Tasks::DatabaseTasks.dump_filename.

    Rafael Mendonça França

  • Remove deprecated Tasks::DatabaseTasks.schema_file.

    Rafael Mendonça França

  • Remove deprecated environment and name arguments from Tasks::DatabaseTasks.schema_up_to_date?.

    Rafael Mendonça França

  • Merging conditions on the same column no longer maintain both conditions,
    and will be consistently replaced by the latter condition.

    # Rails 6.1 (IN clause is replaced by merger side equality condition)
    Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
    # Rails 6.1 (both conflict conditions exists, deprecated)
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
    # Rails 6.1 with rewhere to migrate to Rails 7.0's behavior
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
    # Rails 7.0 (same behavior with IN clause, mergee side condition is consistently replaced)
    Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
    
    *Rafael Mendonça França*
    
    
  • Remove deprecated support to Model.reorder(nil).first to search using non-deterministic order.

    Rafael Mendonça França

  • Remove deprecated rake tasks:

    • db:schema:load_if_ruby
    • db:structure:dump
    • db:structure:load
    • db:structure:load_if_sql
    • db:structure:dump:#{name}
    • db:structure:load:#{name}
    • db:test:load_structure
    • db:test:load_structure:#{name}

    Rafael Mendonça França

  • Remove deprecated DatabaseConfig#config method.

    Rafael Mendonça França

  • Rollback transactions when the block returns earlier than expected.

    Before this change, when a transaction block returned early, the transaction would be committed.

    The problem is that timeouts triggered inside the transaction block was also making the incomplete transaction
    to be committed, so in order to avoid this mistake, the transaction block is rolled back.

    Rafael Mendonça França

  • Add middleware for automatic shard swapping.

    Provides a basic middleware to perform automatic shard swapping. Applications will provide a resolver which will determine for an individual request which shard should be used. Example:

    config.active_record.shard_resolver = ->(request) {
      subdomain = request.subdomain
      tenant = Tenant.find_by_subdomain!(subdomain)
      tenant.shard
    }
    

    See guides for more details.

    Eileen M. Uchitelle, John Crepezzi

  • Remove deprecated support to pass a column to type_cast.

    Rafael Mendonça França

  • Remove deprecated support to type cast to database values ActiveRecord::Base objects.

    Rafael Mendonça França

  • Remove deprecated support to quote ActiveRecord::Base objects.

    Rafael Mendonça França

  • Remove deprecacated support to resolve connection using "primary" as connection specification name.

    Rafael Mendonça França

  • Remove deprecation warning when using :interval column is used in PostgreSQL database.

    Now, interval columns will return ActiveSupport::Duration objects instead of strings.

    To keep the old behavior, you can add this line to your model:

    attribute :column, :string
    

    Rafael Mendonça França

  • Remove deprecated support to YAML load ActiveRecord::Base instance in the Rails 4.2 and 4.1 formats.

    Rafael Mendonça França

  • Remove deprecated option :spec_name in the configs_for method.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.allow_unsafe_raw_sql.

    Rafael Mendonça França

  • Fix regression bug that caused ignoring additional conditions for preloading has_many-through relations.

    Fixes #43132

    Alexander Pauly

  • Fix has_many inversing recursion on models with recursive associations.

    Gannon McGibbon

  • Add accepts_nested_attributes_for support for delegated_type

    class Entry < ApplicationRecord
      delegated_type :entryable, types: %w[ Message Comment ]
      accepts_nested_attributes_for :entryable
    end
    
    entry = Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
    # => #<Entry:0x00>
    # id: 1
    # entryable_id: 1,
    # entryable_type: 'Message'
    # ...>
    
    entry.entryable
    # => #<Message:0x01>
    # id: 1
    # content: 'Hello world'
    # ...>
    

    Previously it would raise an error:

    Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
    # ArgumentError: Cannot build association `entryable'. Are you trying to build a polymorphic one-to-one association?
    

    Sjors Baltus

  • Use subquery for DELETE with GROUP_BY and HAVING clauses.

    Prior to this change, deletes with GROUP_BY and HAVING were returning an error.

    After this change, GROUP_BY and HAVING are valid clauses in DELETE queries, generating the following query:

    DELETE FROM "posts" WHERE "posts"."id" IN (
        SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" GROUP BY "posts"."id" HAVING (count(comments.id) >= 2))
    )  [["flagged", "t"]]
    

    Ignacio Chiazzo Cardarello

  • Use subquery for UPDATE with GROUP_BY and HAVING clauses.

    Prior to this change, updates with GROUP_BY and HAVING were being ignored, generating a SQL like this:

    UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
        SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
    )  [["flagged", "t"]]
    

    After this change, GROUP_BY and HAVING clauses are used as a subquery in updates, like this:

    UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
        SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
        GROUP BY posts.id HAVING (count(comments.id) >= 2)
    )  [["flagged", "t"]]
    

    Ignacio Chiazzo Cardarello

  • Add support for setting the filename of the schema or structure dump in the database config.

    Applications may now set their the filename or path of the schema / structure dump file in their database configuration.

    production:
      primary:
        database: my_db
        schema_dump: my_schema_dump_filename.rb
      animals:
        database: animals_db
        schema_dump: false
    

    The filename set in schema_dump will be used by the application. If set to false the schema will not be dumped. The database tasks are responsible for adding the database directory to the filename. If a full path is provided, the Rails tasks will use that instead of ActiveRecord::DatabaseTasks.db_dir.

    Eileen M. Uchitelle, Ryan Kerr

  • Add ActiveRecord::Base.prohibit_shard_swapping to prevent attempts to change the shard within a block.

    John Crepezzi, Eileen M. Uchitelle

  • Filter unchanged attributes with default function from insert query when partial_inserts is disabled.

    Akshay Birajdar, Jacopo Beschi

  • Add support for FILTER clause (SQL:2003) to Arel.

    Currently supported by PostgreSQL 9.4+ and SQLite 3.30+.

    Andrey Novikov

  • Automatically set timestamps on record creation during bulk insert/upsert

    Prior to this change, only updates during an upsert operation (e.g. upsert_all) would touch timestamps (updated_{at,on}). Now, record creations also touch timestamp columns ({created,updated}_{at,on}).

    This behaviour is controlled by the <model>.record_timestamps config, matching the behaviour of create, update, etc. It can also be overridden by using the record_timestamps: keyword argument.

    Note that this means upsert_all on models with record_timestamps = false will no longer touch updated_{at,on} automatically.

    Sam Bostock

  • Don't require role when passing shard to connected_to.

    connected_to can now be called with a shard only. Note that role is still inherited if connected_to calls are nested.

    Eileen M. Uchitelle

  • Add option to lazily load the schema cache on the connection.

    Previously, the only way to load the schema cache in Active Record was through the Railtie on boot. This option provides the ability to load the schema cache on the connection after it's been established. Loading the cache lazily on the connection can be beneficial for Rails applications that use multiple databases because it will load the cache at the time the connection is established. Currently Railties doesn't have access to the connections before boot.

    To use the cache, set config.active_record.lazily_load_schema_cache = true in your application configuration. In addition a schema_cache_path should be set in your database configuration if you don't want to use the default "db/schema_cache.yml" path.

    Eileen M. Uchitelle

  • Allow automatic inverse_of detection for associations with scopes.

    Automatic inverse_of detection now works for associations with scopes. For
    example, the comments association here now automatically detects
    inverse_of: :post, so we don't need to pass that option:

    class Post < ActiveRecord::Base
      has_many :comments, -> { visible }
    end
    
    class Comment < ActiveRecord::Base
      belongs_to :post
    end
    

    Note that the automatic detection still won't work if the inverse
    association has a scope. In this example a scope on the post association
    would still prevent Rails from finding the inverse for the comments
    association.

    This will be the default for new apps in Rails 7. To opt in:

    config.active_record.automatic_scope_inversing = true
    

    Daniel Colson, Chris Bloom

  • Accept optional transaction args to ActiveRecord::Locking::Pessimistic#with_lock

    #with_lock now accepts transaction options like requires_new:,
    isolation:, and joinable:

    John Mileham

  • Adds support for deferrable foreign key constraints in PostgreSQL.

    By default, foreign key constraints in PostgreSQL are checked after each statement. This works for most use cases,
    but becomes a major limitation when creating related records before the parent record is inserted into the database.
    One example of this is looking up / creating a person via one or more unique alias.

    Person.transaction do
      alias = Alias
        .create_with(user_id: SecureRandom.uuid)
        .create_or_find_by(name: "DHH")
    
      person = Person
        .create_with(name: "David Heinemeier Hansson")
        .create_or_find_by(id: alias.user_id)
    end
    

    Using the default behavior, the transaction would fail when executing the first INSERT statement.

    By passing the :deferrable option to the add_foreign_key statement in migrations, it's possible to defer this
    check.

    add_foreign_key :aliases, :person, deferrable: true
    

    Passing deferrable: true doesn't change the default behavior, but allows manually deferring the check using
    SET CONSTRAINTS ALL DEFERRED within a transaction. This will cause the foreign keys to be checked after the
    transaction.

    It's also possible to adjust the default behavior from an immediate check (after the statement), to a deferred check
    (after the transaction):

    add_foreign_key :aliases, :person, deferrable: :deferred
    

    Benedikt Deicke

  • Allow configuring Postgres password through the socket URL.

    For example:

    ActiveRecord::DatabaseConfigurations::UrlConfig.new(
      :production, :production, 'postgres:///?user=user&password=secret&dbname=app', {}
    ).configuration_hash
    

    will now return,

    { :user=>"user", :password=>"secret", :dbname=>"app", :adapter=>"postgresql" }
    

    Abeid Ahmed

  • PostgreSQL: support custom enum types

    In migrations, use create_enum to add a new enum type, and t.enum to add a column.

    def up
      create_enum :mood, ["happy", "sad"]
    
      change_table :cats do |t|
        t.enum :current_mood, enum_type: "mood", default: "happy", null: false
      end
    end
    

    Enums will be presented correctly in schema.rb. Note that this is only supported by
    the PostgreSQL adapter.

    Alex Ghiculescu

  • Avoid COMMENT statements in PostgreSQL structure dumps

    COMMENT statements are now omitted from the output of db:structure:dump when using PostgreSQL >= 11.
    This allows loading the dump without a pgsql superuser account.

    Fixes #36816, #43107.

    Janosch Müller

  • Add support for generated columns in PostgreSQL adapter

    Generated columns are supported since version 12.0 of PostgreSQL. This adds
    support of those to the PostgreSQL adapter.

    create_table :users do |t|
      t.string :name
      t.virtual :name_upcased, type: :string, as: 'upper(name)', stored: true
    end
    

    Michał Begejowicz

  • Remove warning when overwriting existing scopes

    Removes the following unnecessary warning message that appeared when overwriting existing scopes

    Creating scope :my_scope_name. Overwriting existing method "MyClass.my_scope_name" when overwriting existing scopes
    

    Weston Ganger

  • Use full precision for updated_at in insert_all/upsert_all

    CURRENT_TIMESTAMP provides differing precision depending on the database,
    and not all databases support explicitly specifying additional precision.

    Instead, we delegate to the new connection.high_precision_current_timestamp
    for the SQL to produce a high precision timestamp on the current database.

    Fixes #42992

    Sam Bostock

  • Add ssl support for postgresql database tasks

    Add PGSSLMODE, PGSSLCERT, PGSSLKEY and PGSSLROOTCERT to pg_env from database config
    when running postgresql database tasks.

    # config/database.yml
    
    production:
      sslmode: verify-full
      sslcert: client.crt
      sslkey: client.key
      sslrootcert: ca.crt
    

    Environment variables

    PGSSLMODE=verify-full
    PGSSLCERT=client.crt
    PGSSLKEY=client.key
    PGSSLROOTCERT=ca.crt
    

    Fixes #42994

    Michael Bayucot

  • Avoid scoping update callbacks in ActiveRecord::Relation#update!.

    Making it consistent with how scoping is applied only to the query in ActiveRecord::Relation#update
    and not also to the callbacks from the update itself.

    Dylan Thacker-Smith

  • Fix 2 cases that inferred polymorphic class from the association's foreign_type
    using String#constantize instead of the model's polymorphic_class_for.

    When updating a polymorphic association, the old foreign_type was not inferred correctly when:

    1. touching the previously associated record
    2. updating the previously associated record's counter_cache

    Jimmy Bourassa

  • Add config option for ignoring tables when dumping the schema cache.

    Applications can now be configured to ignore certain tables when dumping the schema cache.

    The configuration option can table an array of tables:

    config.active_record.schema_cache_ignored_tables = ["ignored_table", "another_ignored_table"]
    

    Or a regex:

    config.active_record.schema_cache_ignored_tables = [/^_/]
    

    Eileen M. Uchitelle

  • Make schema cache methods return consistent results.

    Previously the schema cache methods primary_keys, columns, columns_hash, and indexes
    would behave differently than one another when a table didn't exist and differently across
    database adapters. This change unifies the behavior so each method behaves the same regardless
    of adapter.

    The behavior now is:

    columns: (unchanged) raises a db error if the table does not exist.
    columns_hash: (unchanged) raises a db error if the table does not exist.
    primary_keys: (unchanged) returns nil if the table does not exist.
    indexes: (changed for mysql2) returns [] if the table does not exist.

    Eileen M. Uchitelle

  • Reestablish connection to previous database after after running db:schema:load:name

    After running db:schema:load:name the previous connection is restored.

    Jacopo Beschi

  • Add database config option database_tasks

    If you would like to connect to an external database without any database
    management tasks such as schema management, migrations, seeds, etc. you can set
    the per database config option database_tasks: false

    # config/database.yml
    
    production:
      primary:
        database: my_database
        adapter: mysql2
      animals:
        database: my_animals_database
        adapter: mysql2
        database_tasks: false
    

    Weston Ganger

  • Fix ActiveRecord::InternalMetadata to not be broken by config.active_record.record_timestamps = false

    Since the model always create the timestamp columns, it has to set them, otherwise it breaks
    various DB management tasks.

    Fixes #42983

  • Add ActiveRecord::QueryLogs.

    Configurable tags can be automatically added to all SQL queries generated by Active Record.

    # config/application.rb
    module MyApp
      class Application < Rails::Application
        config.active_record.query_log_tags_enabled = true
      end
    end
    

    By default the application, controller and action details are added to the query tags:

    class BooksController < ApplicationController
      def index
        @books = Book.all
      end
    end
    
    GET /books
    # SELECT * FROM books /*application:MyApp;controller:books;action:index*/
    

    Custom tags containing static values and Procs can be defined in the application configuration:

    config.active_record.query_log_tags = [
      :application,
      :controller,
      :action,
      {
        custom_static: "foo",
        custom_dynamic: -> { Time.now }
      }
    ]
    

    Keeran Raj Hawoldar, Eileen M. Uchitelle, Kasper Timm Hansen

  • Added support for multiple databases to rails db:setup and rails db:reset.

    Ryan Hall

  • Add ActiveRecord::Relation#structurally_compatible?.

    Adds a query method by which a user can tell if the relation that they're
    about to use for #or or #and is structurally compatible with the
    receiver.

    Kevin Newton

  • Add ActiveRecord::QueryMethods#in_order_of.

    This allows you to specify an explicit order that you'd like records
    returned in based on a SQL expression. By default, this will be accomplished
    using a case statement, as in:

    Post.in_order_of(:id, [3, 5, 1])
    

    will generate the SQL:

    SELECT "posts".* FROM "posts" ORDER BY CASE "posts"."id" WHEN 3 THEN 1 WHEN 5 THEN 2 WHEN 1 THEN 3 ELSE 4 END ASC
    

    However, because this functionality is built into MySQL in the form of the
    FIELD function, that connection adapter will generate the following SQL
    instead:

    SELECT "posts".* FROM "posts" ORDER BY FIELD("posts"."id", 1, 5, 3) DESC
    

    Kevin Newton

  • Fix eager_loading? when ordering with Symbol.

    eager_loading? is triggered correctly when using order with symbols.

    scope = Post.includes(:comments).order(:"comments.label")
    => true
    

    Jacopo Beschi

  • Two change tracking methods are added for belongs_to associations.

    The association_changed? method (assuming an association named :association) returns true
    if a different associated object has been assigned and the foreign key will be updated in the
    next save.

    The association_previously_changed? method returns true if the previous save updated the
    association to reference a different associated object.

    George Claghorn

  • Add option to disable schema dump per-database.

    Dumping the schema is on by default for all databases in an application. To turn it off for a
    specific database, use the schema_dump option:

    # config/database.yml
    
    production:
      schema_dump: false
    

    Luis Vasconcellos, Eileen M. Uchitelle

  • Fix eager_loading? when ordering with Hash syntax.

    eager_loading? is triggered correctly when using order with hash syntax
    on an outer table.

    Post.includes(:comments).order({ "comments.label": :ASC }).eager_loading?
    # => true
    

    Jacopo Beschi

  • Move the forcing of clear text encoding to the ActiveRecord::Encryption::Encryptor.

    Fixes #42699.

    J Smith

  • partial_inserts is now disabled by default in new apps.

    This will be the default for new apps in Rails 7. To opt in:

    config.active_record.partial_inserts = true
    

    If a migration removes the default value of a column, this option
    would cause old processes to no longer be able to create new records.

    If you need to remove a column, you should first use ignored_columns
    to stop using it.

    Jean Boussier

  • Rails can now verify foreign keys after loading fixtures in tests.

    This will be the default for new apps in Rails 7. To opt in:

    config.active_record.verify_foreign_keys_for_fixtures = true
    

    Tests will not run if there is a foreign key constraint violation in your fixture data.

    The feature is supported by SQLite and PostgreSQL, other adapters can also add support for it.

    Alex Ghiculescu

  • Clear cached has_one association after setting belongs_to association to nil.

    After setting a belongs_to relation to nil and updating an unrelated attribute on the owner,
    the owner should still return nil on the has_one relation.

    Fixes #42597.

    Michiel de Mare

  • OpenSSL constants are now used for Digest computations.

    Dirkjan Bussink

  • Adds support for if_not_exists to add_foreign_key and if_exists to remove_foreign_key.

    Applications can set their migrations to ignore exceptions raised when adding a foreign key
    that already exists or when removing a foreign key that does not exist.

    Example Usage:

    class AddAuthorsForeignKeyToArticles < ActiveRecord::Migration[7.0]
      def change
        add_foreign_key :articles, :authors, if_not_exists: true
      end
    end
    
    class RemoveAuthorsForeignKeyFromArticles < ActiveRecord::Migration[7.0]
      def change
        remove_foreign_key :articles, :authors, if_exists: true
      end
    end
    

    Roberto Miranda

  • Prevent polluting ENV during postgresql structure dump/load.

    Some configuration parameters were provided to pg_dump / psql via
    environment variables which persisted beyond the command being run, and may
    have caused subsequent commands and connections to fail. Tasks running
    across multiple postgresql databases like rails db:test:prepare may have
    been affected.

    Samuel Cochran

  • Set precision 6 by default for datetime columns.

    By default, datetime columns will have microseconds precision instead of seconds precision.

    Roberto Miranda

  • Allow preloading of associations with instance dependent scopes.

    John Hawthorn, John Crepezzi, Adam Hess, Eileen M. Uchitelle, Dinah Shi

  • Do not try to rollback transactions that failed due to a ActiveRecord::TransactionRollbackError.

    Jamie McCarthy

  • Active Record Encryption will now encode values as UTF-8 when using deterministic
    encryption. The encoding is part of the encrypted payload, so different encodings for
    different values result in different ciphertexts. This can break unique constraints and
    queries.

    The new behavior is configurable via active_record.encryption.forced_encoding_for_deterministic_encryption
    that is Encoding::UTF_8 by default. It can be disabled by setting it to nil.

    Jorge Manrubia

  • The MySQL adapter now cast numbers and booleans bind parameters to string for safety reasons.

    When comparing a string and a number in a query, MySQL converts the string to a number. So for
    instance "foo" = 0, will implicitly cast "foo" to 0 and will evaluate to TRUE which can
    lead to security vulnerabilities.

    Active Record already protect against that vulnerability when it knows the type of the column
    being compared, however until now it was still vulnerable when using bind parameters:

    User.where("login_token = ?", 0).first
    

    Would perform:

    SELECT * FROM `users` WHERE `login_token` = 0 LIMIT 1;
    

    Now it will perform:

    SELECT * FROM `users` WHERE `login_token` = '0' LIMIT 1;
    

    Jean Boussier

  • Fixture configurations (_fixture) are now strictly validated.

    If an error will be raised if that entry contains unknown keys while previously it
    would silently have no effects.

    Jean Boussier

  • Add ActiveRecord::Base.update! that works like ActiveRecord::Base.update but raises exceptions.

    This allows for the same behavior as the instance method #update! at a class level.

    Person.update!(:all, state: "confirmed")
    

    Dorian Marié

  • Add ActiveRecord::Base#attributes_for_database.

    Returns attributes with values for assignment to the database.

    Chris Salzberg

  • Use an empty query to check if the PostgreSQL connection is still active.

    An empty query is faster than SELECT 1.

    Heinrich Lee Yu

  • Add ActiveRecord::Base#previously_persisted?.

    Returns true if the object has been previously persisted but now it has been deleted.

  • Deprecate partial_writes in favor of partial_inserts and partial_updates.

    This allows to have a different behavior on update and create.

    Jean Boussier

  • Fix compatibility with psych >= 4.

    Starting in Psych 4.0.0 YAML.load behaves like YAML.safe_load. To preserve compatibility,
    Active Record's schema cache loader and YAMLColumn now uses YAML.unsafe_load if available.

    Jean Boussier

  • ActiveRecord::Base.logger is now a class_attribute.

    This means it can no longer be accessed directly through @@logger, and that setting logger =
    on a subclass won't change the parent's logger.

    Jean Boussier

  • Add .asc.nulls_first for all databases. Unfortunately MySQL still doesn't like nulls_last.

    Keenan Brock

  • Improve performance of one? and many? by limiting the generated count query to 2 results.

    Gonzalo Riestra

  • Don't check type when using if_not_exists on add_column.

    Previously, if a migration called add_column with the if_not_exists option set to true
    the column_exists? check would look for a column with the same name and type as the migration.

    Recently it was discovered that the type passed to the migration is not always the same type
    as the column after migration. For example a column set to :mediumblob in the migration will
    be casted to binary when calling column.type. Since there is no straightforward way to cast
    the type to the database type without running the migration, we opted to drop the type check from
    add_column. This means that migrations adding a duplicate column with a different type will no
    longer raise an error.

    Eileen M. Uchitelle

  • Log a warning message when running SQLite in production.

    Using SQLite in production ENV is generally discouraged. SQLite is also the default adapter
    in a new Rails application.
    For the above reasons log a warning message when running SQLite in production.

    The warning can be disabled by setting config.active_record.sqlite3_production_warning=false.

    Jacopo Beschi

  • Add option to disable joins for has_one associations.

    In a multiple database application, associations can't join across
    databases. When set, this option instructs Rails to generate 2 or
    more queries rather than generating joins for has_one associations.

    Set the option on a has one through association:

    class Person
      has_one :dog
      has_one :veterinarian, through: :dog, disable_joins: true
    end
    

    Then instead of generating join SQL, two queries are used for @person.veterinarian:

    SELECT "dogs"."id" FROM "dogs" WHERE "dogs"."person_id" = ?  [["person_id", 1]]
    SELECT "veterinarians".* FROM "veterinarians" WHERE "veterinarians"."dog_id" = ?  [["dog_id", 1]]
    

    Sarah Vessels, Eileen M. Uchitelle

  • Arel::Visitors::Dot now renders a complete set of properties when visiting
    Arel::Nodes::SelectCore, SelectStatement, InsertStatement, UpdateStatement, and
    DeleteStatement, which fixes #42026. Previously, some properties were omitted.

    Mike Dalessio

  • Arel::Visitors::Dot now supports Arel::Nodes::Bin, Case, CurrentRow, Distinct,
    DistinctOn, Else, Except, InfixOperation, Intersect, Lock, NotRegexp, Quoted,
    Regexp, UnaryOperation, Union, UnionAll, When, and With. Previously, these node
    types caused an exception to be raised by Arel::Visitors::Dot#accept.

    Mike Dalessio

  • Optimize remove_columns to use a single SQL statement.

    remove_columns :my_table, :col_one, :col_two
    

    Now results in the following SQL:

    ALTER TABLE "my_table" DROP COLUMN "col_one", DROP COLUMN "col_two"
    

    Jon Dufresne

  • Ensure has_one autosave association callbacks get called once.

    Change the has_one autosave callback to be non cyclic as well.
    By doing this the autosave callback are made more consistent for
    all 3 cases: has_many, has_one, and belongs_to.

    Petrik de Heus

  • Add option to disable joins for associations.

    In a multiple database application, associations can't join across
    databases. When set, this option instructs Rails to generate 2 or
    more queries rather than generating joins for associations.

    Set the option on a has many through association:

    class Dog
      has_many :treats, through: :humans, disable_joins: true
      has_many :humans
    end
    

    Then instead of generating join SQL, two queries are used for @dog.treats:

    SELECT "humans"."id" FROM "humans" WHERE "humans"."dog_id" = ?  [["dog_id", 1]]
    SELECT "treats".* FROM "treats" WHERE "treats"."human_id" IN (?, ?, ?)  [["human_id", 1], ["human_id", 2], ["human_id", 3]]
    

    Eileen M. Uchitelle, Aaron Patterson, Lee Quarella

  • Add setting for enumerating column names in SELECT statements.

    Adding a column to a PostgreSQL database, for example, while the application is running can
    change the result of wildcard SELECT * queries, which invalidates the result
    of cached prepared statements and raises a PreparedStatementCacheExpired error.

    When enabled, Active Record will avoid wildcards and always include column names
    in SELECT queries, which will return consistent results and avoid prepared
    statement errors.

    Before:

    Book.limit(5)
    # SELECT * FROM books LIMIT 5
    

    After:

    # config/application.rb
    module MyApp
      class Application < Rails::Application
        config.active_record.enumerate_columns_in_select_statements = true
      end
    end
    
    # or, configure per-model
    class Book < ApplicationRecord
      self.enumerate_columns_in_select_statements = true
    end
    
    Book.limit(5)
    # SELECT id, author_id, name, format, status, language, etc FROM books LIMIT 5
    

    Matt Duszynski

  • Allow passing SQL as on_duplicate value to #upsert_all to make it possible to use raw SQL to update columns on conflict:

    Book.upsert_all(
      [{ id: 1, status: 1 }, { id: 2, status: 1 }],
      on_duplicate: Arel.sql("status = GREATEST(books.status, EXCLUDED.status)")
    )
    

    Vladimir Dementyev

  • Allow passing SQL as returning statement to #upsert_all:

    Article.insert_all(
      [
        { title: "Article 1", slug: "article-1", published: false },
        { title: "Article 2", slug: "article-2", published: false }
      ],
      returning: Arel.sql("id, (xmax = '0') as inserted, name as new_name")
    )
    

    Vladimir Dementyev

  • Deprecate legacy_connection_handling.

    Eileen M. Uchitelle

  • Add attribute encryption support.

    Encrypted attributes are declared at the model level. These
    are regular Active Record attributes backed by a column with
    the same name. The system will transparently encrypt these
    attributes before saving them into the database and will
    decrypt them when retrieving their values.

    class Person < ApplicationRecord
      encrypts :name
      encrypts :email_address, deterministic: true
    end
    

    You can learn more in the Active Record Encryption
    guide
    .

    Jorge Manrubia

  • Changed Arel predications contains and overlaps to use
    quoted_node so that PostgreSQL arrays are quoted properly.

    Bradley Priest

  • Add mode argument to record level strict_loading!.

    This argument can be used when enabling strict loading for a single record
    to specify that we only want to raise on n plus one queries.

    developer.strict_loading!(mode: :n_plus_one_only)
    
    developer.projects.to_a # Does not raise
    developer.projects.first.client # Raises StrictLoadingViolationError
    

    Previously, enabling strict loading would cause any lazily loaded
    association to raise an error. Using n_plus_one_only mode allows us to
    lazily load belongs_to, has_many, and other associations that are fetched
    through a single query.

    Dinah Shi

  • Fix Float::INFINITY assignment to datetime column with postgresql adapter.

    Before:

    # With this config
    ActiveRecord::Base.time_zone_aware_attributes = true
    
    # and the following schema:
    create_table "postgresql_infinities" do |t|
      t.datetime "datetime"
    end
    
    # This test fails
    record = PostgresqlInfinity.create!(datetime: Float::INFINITY)
    assert_equal Float::INFINITY, record.datetime # record.datetime gets nil
    

    After this commit, record.datetime gets Float::INFINITY as expected.

    Shunichi Ikegami

  • Type cast enum values by the original attribute type.

    The notable thing about this change is that unknown labels will no longer match 0 on MySQL.

    class Book < ActiveRecord::Base
      enum :status, { proposed: 0, written: 1, published: 2 }
    end
    

    Before:

    # SELECT `books`.* FROM `books` WHERE `books`.`status` = 'prohibited' LIMIT 1
    Book.find_by(status: :prohibited)
    # => #<Book id: 1, status: "proposed", ...> (for mysql2 adapter)
    # => ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR:  invalid input syntax for type integer: "prohibited" (for postgresql adapter)
    # => nil (for sqlite3 adapter)
    

    After:

    # SELECT `books`.* FROM `books` WHERE `books`.`status` IS NULL LIMIT 1
    Book.find_by(status: :prohibited)
    # => nil (for all adapters)
    

    Ryuta Kamizono

  • Fixtures for has_many :through associations now load timestamps on join tables.

    Given this fixture:

    ### monkeys.yml
    george:
      name: George the Monkey
      fruits: apple
    
    ### fruits.yml
    apple:
      name: apple
    

    If the join table (fruit_monkeys) contains created_at or updated_at columns,
    these will now be populated when loading the fixture. Previously, fixture loading
    would crash if these columns were required, and leave them as null otherwise.

    Alex Ghiculescu

  • Allow applications to configure the thread pool for async queries.

    Some applications may want one thread pool per database whereas others want to use
    a single global thread pool for all queries. By default, Rails will set async_query_executor
    to nil which will not initialize any executor. If load_async is called and no executor
    has been configured, the query will be executed in the foreground.

    To create one thread pool for all database connections to use applications can set
    config.active_record.async_query_executor to :global_thread_pool and optionally define
    config.active_record.global_executor_concurrency. This defaults to 4. For applications that want
    to have a thread pool for each database connection, config.active_record.async_query_executor can
    be set to :multi_thread_pool. The configuration for each thread pool is set in the database
    configuration.

    Eileen M. Uchitelle

  • Allow new syntax for enum to avoid leading _ from reserved options.

    Before:

    class Book < ActiveRecord::Base
      enum status: [ :proposed, :written ], _prefix: true, _scopes: false
      enum cover: [ :hard, :soft ], _suffix: true, _default: :hard
    end
    

    After:

    class Book < ActiveRecord::Base
      enum :status, [ :proposed, :written ], prefix: true, scopes: false
      enum :cover, [ :hard, :soft ], suffix: true, default: :hard
    end
    

    Ryuta Kamizono

  • Add ActiveRecord::Relation#load_async.

    This method schedules the query to be performed asynchronously from a thread pool.

    If the result is accessed before a background thread had the opportunity to perform
    the query, it will be performed in the foreground.

    This is useful for queries that can be performed long enough before their result will be
    needed, or for controllers which need to perform several independent queries.

    def index
      @categories = Category.some_complex_scope.load_async
      @posts = Post.some_complex_scope.load_async
    end
    

    Active Record logs will also include timing info for the duration of how long
    the main thread had to wait to access the result. This timing is useful to know
    whether or not it's worth to load the query asynchronously.

    DEBUG -- :   Category Load (62.1ms)  SELECT * FROM `categories` LIMIT 50
    DEBUG -- :   ASYNC Post Load (64ms) (db time 126.1ms)  SELECT * FROM `posts` LIMIT 100
    

    The duration in the first set of parens is how long the main thread was blocked
    waiting for the results, and the second set of parens with "db time" is how long
    the entire query took to execute.

    Jean Boussier

  • Implemented ActiveRecord::Relation#excluding method.

    This method excludes the specified record (or collection of records) from
    the resulting relation:

    Post.excluding(post)
    Post.excluding(post_one, post_two)
    

    Also works on associations:

    post.comments.excluding(comment)
    post.comments.excluding(comment_one, comment_two)
    

    This is short-hand for Post.where.not(id: post.id) (for a single record)
    and Post.where.not(id: [post_one.id, post_two.id]) (for a collection).

    Glen Crawford

  • Skip optimised #exist? query when #include? is called on a relation
    with a having clause.

    Relations that have aliased select values AND a having clause that
    references an aliased select value would generate an error when
    #include? was called, due to an optimisation that would generate
    call #exists? on the relation instead, which effectively alters
    the select values of the query (and thus removes the aliased select
    values), but leaves the having clause intact. Because the having
    clause is then referencing an aliased column that is no longer
    present in the simplified query, an ActiveRecord::InvalidStatement
    error was raised.

    A sample query affected by this problem:

    Author.select('COUNT(*) as total_posts', 'authors.*')
          .joins(:posts)
          .group(:id)
          .having('total_posts > 2')
          .include?(Author.first)
    

    This change adds an addition check to the condition that skips the
    simplified #exists? query, which simply checks for the presence of
    a having clause.

    Fixes #41417.

    Michael Smart

  • Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted
    without Rails knowledge (e.g., if app gets killed during long-running query or due to Rack::Timeout), app won't end
    up in perpetual crash state for being inconsistent with PostgreSQL.

    wbharding, Martin Tepper

  • Add ability to apply scoping to all_queries.

    Some applications may want to use the scoping method but previously it only
    worked on certain types of queries. This change allows the scoping method to apply
    to all queries for a model in a block.

    Post.where(blog_id: post.blog_id).scoping(all_queries: true) do
      post.update(title: "a post title") # adds `posts.blog_id = 1` to the query
    end
    

    Eileen M. Uchitelle

  • ActiveRecord::Calculations.calculate called with :average
    (aliased as ActiveRecord::Calculations.average) will now use column-based
    type casting. This means that floating-point number columns will now be
    aggregated as Float and decimal columns will be aggregated as BigDecimal.

    Integers are handled as a special case returning BigDecimal always
    (this was the case before already).

    # With the following schema:
    create_table "measurements" do |t|
      t.float "temperature"
    end
    
    # Before:
    Measurement.average(:temperature).class
    # => BigDecimal
    
    # After:
    Measurement.average(:temperature).class
    # => Float
    

    Before this change, Rails just called to_d on average aggregates from the
    database adapter. This is not the case anymore. If you relied on that kind
    of magic, you now need to register your own ActiveRecord::Type
    (see ActiveRecord::Attributes::ClassMethods for documentation).

    Josua Schmid

  • PostgreSQL: introduce ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_type.

    This setting controls what native type Active Record should use when you call datetime in
    a migration or schema. It takes a symbol which must correspond to one of the configured
    NATIVE_DATABASE_TYPES. The default is :timestamp, meaning t.datetime in a migration
    will create a "timestamp without time zone" column. To use "timestamp with time zone",
    change this to :timestamptz in an initializer.

    You should run bin/rails db:migrate to rebuild your schema.rb if you change this.

    Alex Ghiculescu

  • PostgreSQL: handle timestamp with time zone columns correctly in schema.rb.

    Previously they dumped as t.datetime :column_name, now they dump as t.timestamptz :column_name,
    and are created as timestamptz columns when the schema is loaded.

    Alex Ghiculescu

  • Removing trailing whitespace when matching columns in
    ActiveRecord::Sanitization.disallow_raw_sql!.

    Gannon McGibbon, Adrian Hirt

  • Expose a way for applications to set a primary_abstract_class.

    Multiple database applications that use a primary abstract class that is not
    named ApplicationRecord can now set a specific class to be the primary_abstract_class.

    class PrimaryApplicationRecord
      self.primary_abstract_class
    end
    

    When an application boots it automatically connects to the primary or first database in the
    database configuration file. In a multiple database application that then call connects_to
    needs to know that the default connection is the same as the ApplicationRecord connection.
    However, some applications have a differently named ApplicationRecord. This prevents Active
    Record from opening duplicate connections to the same database.

    Eileen M. Uchitelle, John Crepezzi

  • Support hash config for structure_dump_flags and structure_load_flags flags.
    Now that Active Record supports multiple databases configuration,
    we need a way to pass specific flags for dump/load databases since
    the options are not the same for different adapters.
    We can use in the original way:

    ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-defaults', '--skip-add-drop-table']
    # or
    ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = '--no-defaults --skip-add-drop-table'
    

    And also use it passing a hash, with one or more keys, where the key
    is the adapter

    ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = {
      mysql2: ['--no-defaults', '--skip-add-drop-table'],
      postgres: '--no-tablespaces'
    }
    

    Gustavo Gonzalez

  • Connection specification now passes the "url" key as a configuration for the
    adapter if the "url" protocol is "jdbc", "http", or "https". Previously only
    urls with the "jdbc" prefix were passed to the Active Record Adapter, others
    are assumed to be adapter specification urls.

    Fixes #41137.

    Jonathan Bracy

  • Allow to opt-out of strict_loading mode on a per-record base.

    This is useful when strict loading is enabled application wide or on a
    model level.

    class User < ApplicationRecord
      has_many :bookmarks
      has_many :articles, strict_loading: true
    end
    
    user = User.first
    user.articles                        # => ActiveRecord::StrictLoadingViolationError
    user.bookmarks                       # => #<ActiveRecord::Associations::CollectionProxy>
    
    user.strict_loading!(true)           # => true
    user.bookmarks                       # => ActiveRecord::StrictLoadingViolationError
    
    user.strict_loading!(false)          # => false
    user.bookmarks                       # => #<ActiveRecord::Associations::CollectionProxy>
    user.articles.strict_loading!(false) # => #<ActiveRecord::Associations::CollectionProxy>
    

    Ayrton De Craene

  • Add FinderMethods#sole and #find_sole_by to find and assert the
    presence of exactly one record.

    Used when you need a single row, but also want to assert that there aren't
    multiple rows matching the condition; especially for when database
    constraints aren't enough or are impractical.

    Product.where(["price = %?", price]).sole
    # => ActiveRecord::RecordNotFound      (if no Product with given price)
    # => #<Product ...>                    (if one Product with given price)
    # => ActiveRecord::SoleRecordExceeded  (if more than one Product with given price)
    
    user.api_keys.find_sole_by(key: key)
    # as above
    

    Asherah Connor

  • Makes ActiveRecord::AttributeMethods::Query respect the getter overrides defined in the model.

    Before:

    class User
      def admin
        false # Overriding the getter to always return false
      end
    end
    
    user = User.first
    user.update(admin: true)
    
    user.admin # false (as expected, due to the getter overwrite)
    user.admin? # true (not expected, returned the DB column value)
    

    After this commit, user.admin? above returns false, as expected.

    Fixes #40771.

    Felipe

  • Allow delegated_type to be specified primary_key and foreign_key.

    Since delegated_type assumes that the foreign_key ends with _id,
    singular_id defined by it does not work when the foreign_key does
    not end with id. This change fixes it by taking into account
    primary_key and foreign_key in the options.

    Ryota Egusa

  • Expose an invert_where method that will invert all scope conditions.

    class User
      scope :active, -> { where(accepted: true, locked: false) }
    end
    
    User.active
    # ... WHERE `accepted` = 1 AND `locked` = 0
    
    User.active.invert_where
    # ... WHERE NOT (`accepted` = 1 AND `locked` = 0)
    

    Kevin Deisz

  • Restore possibility of passing false to :polymorphic option of belongs_to.

    Previously, passing false would trigger the option validation logic
    to throw an error saying :polymorphic would not be a valid option.

    glaszig

  • Remove deprecated database kwarg from connected_to.

    Eileen M. Uchitelle, John Crepezzi

  • Allow adding nonnamed expression indexes to be revertible.

    Previously, the following code would raise an error, when executed while rolling back,
    and the index name should be specified explicitly. Now, the index name is inferred
    automatically.

    add_index(:items, "to_tsvector('english', description)")
    

    Fixes #40732.

    fatkodima

  • Only warn about negative enums if a positive form that would cause conflicts exists.

    Fixes #39065.

    Alex Ghiculescu

  • Add option to run default_scope on all queries.

    Previously, a default_scope would only run on select or insert queries. In some cases, like non-Rails tenant sharding solutions, it may be desirable to run default_scope on all queries in order to ensure queries are including a foreign key for the shard (i.e. blog_id).

    Now applications can add an option to run on all queries including select, insert, delete, and update by adding an all_queries option to the default scope definition.

    class Article < ApplicationRecord
      default_scope -> { where(blog_id: Current.blog.id) }, all_queries: true
    end
    

    Eileen M. Uchitelle

  • Add where.associated to check for the presence of an association.

    # Before:
    account.users.joins(:contact).where.not(contact_id: nil)
    
    # After:
    account.users.where.associated(:contact)
    

    Also mirrors where.missing.

    Kasper Timm Hansen

  • Allow constructors (build_association and create_association) on
    has_one :through associations.

    Santiago Perez Perret

Active Storage

  • Support transforming empty-ish has_many_attached value into [] (e.g. [""]).

    @user.highlights = [""]
    @user.highlights # => []
    

    Sean Doyle

  • Add ActiveStorage::Blob.compose to concatenate multiple blobs.

    Gannon McGibbon

  • Setting custom metadata on blobs are now persisted to remote storage.

    joshuamsager

  • Support direct uploads to multiple services.

    Dmitry Tsepelev

  • Invalid default content types are deprecated

    Blobs created with content_type image/jpg, image/pjpeg, image/bmp, text/javascript will now produce
    a deprecation warning, since these are not valid content types.

    These content types will be removed from the defaults in Rails 7.1.

    You can set config.active_storage.silence_invalid_content_types_warning = true to dismiss the warning.

    Alex Ghiculescu

  • Emit Active Support instrumentation events from Active Storage analyzers.

    Fixes #42930

    Shouichi Kamiya

  • Add support for byte range requests

    Tom Prats

  • Attachments can be deleted after their association is no longer defined.

    Fixes #42514

    Don Sisco

  • Make vips the default variant processor for new apps.

    See the upgrade guide for instructions on converting from mini_magick to vips. mini_magick is
    not deprecated, existing apps can keep using it.

    Breno Gazzola

  • Deprecate ActiveStorage::Current.host in favor of ActiveStorage::Current.url_options which accepts
    a host, protocol and port.

    Santiago Bartesaghi

  • Allow using IAM when signing URLs with GCS.

    gcs:
      service: GCS
      ...
      iam: true
    

    RRethy

  • OpenSSL constants are now used for Digest computations.

    Dirkjan Bussink

  • Deprecate config.active_storage.replace_on_assign_to_many. Future versions of Rails
    will behave the same way as when the config is set to true.

    Santiago Bartesaghi

  • Remove deprecated methods: build_after_upload, create_after_upload! in favor of create_and_upload!,
    and service_url in favor of url.

    Santiago Bartesaghi

  • Add support of strict_loading_by_default to ActiveStorage::Representations controllers.

    Anton Topchii, Andrew White

  • Allow to detach an attachment when record is not persisted.

    Jacopo Beschi

  • Use libvips instead of ImageMagick to analyze images when active_storage.variant_processor = vips.

    Breno Gazzola

  • Add metadata value for presence of video channel in video blobs.

    The metadata attribute of video blobs has a new boolean key named video that is set to
    true if the file has an video channel and false if it doesn't.

    Breno Gazzola

  • Deprecate usage of purge and purge_later from the association extension.

    Jacopo Beschi

  • Passing extra parameters in ActiveStorage::Blob#url to S3 Client.

    This allows calls of ActiveStorage::Blob#url to have more interaction with
    the S3 Presigner, enabling, amongst other options, custom S3 domain URL
    Generation.

    blob = ActiveStorage::Blob.last
    
    blob.url # => https://<bucket-name>.s3.<region>.amazonaws.com/<key>
    blob.url(virtual_host: true) # => # => https://<bucket-name>/<key>
    

    josegomezr

  • Allow setting a Cache-Control on files uploaded to GCS.

    gcs:
      service: GCS
      ...
      cache_control: "public, max-age=3600"
    

    maleblond

  • The parameters sent to ffmpeg for generating a video preview image are now
    configurable under config.active_storage.video_preview_arguments.

    Brendon Muir

  • The ActiveStorage video previewer will now use scene change detection to generate
    better preview images (rather than the previous default of using the first frame
    of the video). This change requires FFmpeg v3.4+.

    Jonathan Hefner

  • Add support for ActiveStorage expiring URLs.

    rails_blob_path(user.avatar, disposition: "attachment", expires_in: 30.minutes)
    
    <%= image_tag rails_blob_path(user.avatar.variant(resize: "100x100"), expires_in: 30.minutes) %>
    

    If you want to set default expiration time for ActiveStorage URLs throughout your application, set config.active_storage.urls_expire_in.

    aki77

  • Allow to purge an attachment when record is not persisted for has_many_attached.

    Jacopo Beschi

  • Add with_all_variant_records method to eager load all variant records on an attachment at once.
    with_attached_image scope now eager loads variant records if using variant tracking.

    Alex Ghiculescu

  • Add metadata value for presence of audio channel in video blobs.

    The metadata attribute of video blobs has a new boolean key named audio that is set to
    true if the file has an audio channel and false if it doesn't.

    Breno Gazzola

  • Adds analyzer for audio files.

    Breno Gazzola

  • Respect Active Record's primary_key_type in Active Storage migrations.

    fatkodima

  • Allow expires_in for ActiveStorage signed ids.

    aki77

  • Allow to purge an attachment when record is not persisted for has_one_attached.

    Jacopo Beschi

  • Add a load hook called active_storage_variant_record (providing ActiveStorage::VariantRecord)
    to allow for overriding aspects of the ActiveStorage::VariantRecord class. This makes
    ActiveStorage::VariantRecord consistent with ActiveStorage::Blob and ActiveStorage::Attachment
    that already have load hooks.

    Brendon Muir

  • ActiveStorage::PreviewError is raised when a previewer is unable to generate a preview image.

    Alex Robbin

  • Add ActiveStorage::Streaming module that can be included in a controller to get access to #send_blob_stream,
    which wraps the new ActionController::Base#send_stream method to stream a blob from cloud storage:

    class MyPublicBlobsController < ApplicationController
      include ActiveStorage::SetBlob, ActiveStorage::Streaming
    
      def show
        http_cache_forever(public: true) do
          send_blob_stream @blob, disposition: params[:disposition]
        end
      end
    end
    

    DHH

  • Add ability to use pre-defined variants.

    class User < ActiveRecord::Base
      has_one_attached :avatar do |attachable|
        attachable.variant :thumb, resize: "100x100"
        attachable.variant :medium, resize: "300x300", monochrome: true
      end
    end
    
    class Gallery < ActiveRecord::Base
      has_many_attached :photos do |attachable|
        attachable.variant :thumb, resize: "100x100"
        attachable.variant :medium, resize: "300x300", monochrome: true
      end
    end
    
    <%= image_tag user.avatar.variant(:thumb) %>
    

    fatkodima

  • After setting config.active_storage.resolve_model_to_route = :rails_storage_proxy
    rails_blob_path and rails_representation_path will generate proxy URLs by default.

    Ali Ismayilov

  • Declare ActiveStorage::FixtureSet and ActiveStorage::FixtureSet.blob to
    improve fixture integration.

    Sean Doyle

Active Support

  • Fix ActiveSupport::Duration.build to support negative values.

    The algorithm to collect the parts of the ActiveSupport::Duration
    ignored the sign of the value and accumulated incorrect part values. This
    impacted ActiveSupport::Duration#sum (which is dependent on parts) but
    not ActiveSupport::Duration#eql? (which is dependent on value).

    Caleb Buxton, Braden Staudacher

  • Deprecate passing a format to #to_s in favor of #to_formatted_s in Array, Range, Date, DateTime, Time,
    BigDecimal, Float and, Integer.

    Rafael Mendonça França

  • Document ActiveSupport::Testing::Deprecation.

    Sam Bostock & Sam Jordan

  • Add Pathname#existence.

    Pathname.new("file").existence&.read
    

    Timo Schilling

  • Remove deprecate ActiveSupport::Multibyte::Unicode.default_normalization_form.

    Rafael Mendonça França

  • Remove deprecated support to use Range#include? to check the inclusion of a value in
    a date time range is deprecated.

    Rafael Mendonça França

  • Remove deprecated URI.parser.

    Rafael Mendonça França

  • Remove deprecated config.active_support.use_sha1_digests.

    Rafael Mendonça França

  • Invoking Object#with_options without a &block argument returns the
    ActiveSupport::OptionMerger instance.

    Sean Doyle

  • Rails.application.executor hooks can now be called around every test

    This helps to better simulate request or job local state being reset around tests and prevents state
    leaking from one test to another.

    However it requires the executor hooks executed in the test environment to be re-entrant.

    To enable this, set config.active_support.executor_around_test_case = true (this is the default in Rails 7).

    Jean Boussier

  • ActiveSupport::DescendantsTracker now mostly delegate to Class#descendants on Ruby 3.1

    Ruby now provides a fast Class#descendants making ActiveSupport::DescendantsTracker mostly useless.

    As a result the following methods are deprecated:

    • ActiveSupport::DescendantsTracker.direct_descendants
    • ActiveSupport::DescendantsTracker#direct_descendants

    Jean Boussier

  • Fix the Digest::UUID.uuid_from_hash behavior for namespace IDs that are different from the ones defined on Digest::UUID.

    The new behavior will be enabled by setting the
    config.active_support.use_rfc4122_namespaced_uuids option to true
    and is the default for new apps.

    The old behavior is the default for upgraded apps and will output a
    deprecation warning every time a value that is different than one of
    the constants defined on the Digest::UUID extension is used as the
    namespace ID.

    Alex Robbin, Erich Soares Machado, Eugene Kenny

  • ActiveSupport::Inflector::Inflections#clear(:acronyms) is now supported,
    and inflector.clear / inflector.clear(:all) also clears acronyms.

    Alex Ghiculescu, Oliver Peate

  • ActiveSupport::Dependencies no longer installs a const_missing hook. Before this, you could push to the autoload paths and have constants autoloaded. This feature, known as the classic autoloader, has been removed.

    Xavier Noria

  • Private internal classes of ActiveSupport::Dependencies have been deleted, like ActiveSupport::Dependencies::Reference, ActiveSupport::Dependencies::Blamable, and others.

    Xavier Noria

  • The private API of ActiveSupport::Dependencies has been deleted. That includes methods like hook!, unhook!, depend_on, require_or_load, mechanism, and many others.

    Xavier Noria

  • Improves the performance of ActiveSupport::NumberHelper formatters by avoiding the use of exceptions as flow control.

    Mike Dalessio

  • Removed rescue block from ActiveSupport::Cache::RedisCacheStore#handle_exception

    Previously, if you provided a error_handler to redis_cache_store, any errors thrown by
    the error handler would be rescued and logged only. Removed the rescue clause from handle_exception
    to allow these to be thrown.

    Nicholas A. Stuart

  • Allow entirely opting out of deprecation warnings.

    Previously if you did app.config.active_support.deprecation = :silence, some work would
    still be done on each call to ActiveSupport::Deprecation.warn. In very hot paths, this could
    cause performance issues.

    Now, you can make ActiveSupport::Deprecation.warn a no-op:

    config.active_support.report_deprecations = false
    

    This is the default in production for new apps. It is the equivalent to:

    config.active_support.deprecation = :silence
    config.active_support.disallowed_deprecation = :silence
    

    but will take a more optimised code path.

    Alex Ghiculescu

  • Faster tests by parallelizing only when overhead is justified by the number
    of them.

    Running tests in parallel adds overhead in terms of database
    setup and fixture loading. Now, Rails will only parallelize test executions when
    there are enough tests to make it worth it.

    This threshold is 50 by default, and is configurable via config setting in
    your test.rb:

    config.active_support.test_parallelization_threshold = 100
    

    It's also configurable at the test case level:

    class ActiveSupport::TestCase
      parallelize threshold: 100
    end
    

    Jorge Manrubia

  • OpenSSL constants are now used for Digest computations.

    Dirkjan Bussink

  • TimeZone.iso8601 now accepts valid ordinal values similar to Ruby's Date._iso8601 method.
    A valid ordinal value will be converted to an instance of TimeWithZone using the :year
    and :yday fragments returned from Date._iso8601.

    twz = ActiveSupport::TimeZone["Eastern Time (US & Canada)"].iso8601("21087")
    twz.to_a[0, 6] == [0, 0, 0, 28, 03, 2021]
    

    Steve Laing

  • Time#change and methods that call it (e.g. Time#advance) will now
    return a Time with the timezone argument provided, if the caller was
    initialized with a timezone argument.

    Fixes #42467.

    Alex Ghiculescu

  • Allow serializing any module or class to JSON by name.

    Tyler Rick, Zachary Scott

  • Raise ActiveSupport::EncryptedFile::MissingKeyError when the
    RAILS_MASTER_KEY environment variable is blank (e.g. "").

    Sunny Ripert

  • The from: option is added to ActiveSupport::TestCase#assert_no_changes.

    It permits asserting on the initial value that is expected not to change.

    assert_no_changes -> { Status.all_good? }, from: true do
      post :create, params: { status: { ok: true } }
    end
    

    George Claghorn

  • Deprecate ActiveSupport::SafeBuffer's incorrect implicit conversion of objects into string.

    Except for a few methods like String#%, objects must implement #to_str
    to be implicitly converted to a String in string operations. In some
    circumstances ActiveSupport::SafeBuffer was incorrectly calling the
    explicit conversion method (#to_s) on them. This behavior is now
    deprecated.

    Jean Boussier

  • Allow nested access to keys on Rails.application.credentials.

    Previously only top level keys in credentials.yml.enc could be accessed with method calls. Now any key can.

    For example, given these secrets:

    aws:
      access_key_id: 123
      secret_access_key: 345
    

    Rails.application.credentials.aws.access_key_id will now return the same thing as
    Rails.application.credentials.aws[:access_key_id].

    Alex Ghiculescu

  • Added a faster and more compact ActiveSupport::Cache serialization format.

    It can be enabled with config.active_support.cache_format_version = 7.0 or
    config.load_defaults 7.0. Regardless of the configuration Active Support
    7.0 can read cache entries serialized by Active Support 6.1 which allows to
    upgrade without invalidating the cache. However Rails 6.1 can't read the
    new format, so all readers must be upgraded before the new format is enabled.

    Jean Boussier

  • Add Enumerable#sole, per ActiveRecord::FinderMethods#sole. Returns the
    sole item of the enumerable, raising if no items are found, or if more than
    one is.

    Asherah Connor

  • Freeze ActiveSupport::Duration#parts and remove writer methods.

    Durations are meant to be value objects and should not be mutated.

    Andrew White

  • Fix ActiveSupport::TimeZone#utc_to_local with fractional seconds.

    When utc_to_local_returns_utc_offset_times is false and the time
    instance had fractional seconds the new UTC time instance was out by
    a factor of 1,000,000 as the Time.utc constructor takes a usec
    value and not a fractional second value.

    Andrew White

  • Add expires_at argument to ActiveSupport::Cache write and fetch to set a cache entry TTL as an absolute time.

    Rails.cache.write(key, value, expires_at: Time.now.at_end_of_hour)
    

    Jean Boussier

  • Deprecate ActiveSupport::TimeWithZone.name so that from Rails 7.1 it will use the default implementation.

    Andrew White

  • Deprecates Rails custom Enumerable#sum and Array#sum in favor of Ruby's native implementation which
    is considerably faster.

    Ruby requires an initializer for non-numeric type as per examples below:

    %w[foo bar].sum('')
    # instead of %w[foo bar].sum
    
    [[1, 2], [3, 4, 5]].sum([])
    # instead of [[1, 2], [3, 4, 5]].sum
    

    Alberto Mota

  • Tests parallelization is now disabled when running individual files to prevent the setup overhead.

    It can still be enforced if the environment variable PARALLEL_WORKERS is present and set to a value greater than 1.

    Ricardo Díaz

  • Fix proxying keyword arguments in ActiveSupport::CurrentAttributes.

    Marcin Kołodziej

  • Add Enumerable#maximum and Enumerable#minimum to easily calculate the maximum or minimum from extracted
    elements of an enumerable.

    payments = [Payment.new(5), Payment.new(15), Payment.new(10)]
    
    payments.minimum(:price) # => 5
    payments.maximum(:price) # => 15
    

    This also allows passing enumerables to fresh_when and stale? in Action Controller.
    See PR #41404 for an example.

    Ayrton De Craene

  • ActiveSupport::Cache::MemCacheStore now accepts an explicit nil for its addresses argument.

    config.cache_store = :mem_cache_store, nil
    
    # is now equivalent to
    
    config.cache_store = :mem_cache_store
    
    # and is also equivalent to
    
    config.cache_store = :mem_cache_store, ENV["MEMCACHE_SERVERS"] || "localhost:11211"
    
    # which is the fallback behavior of Dalli
    

    This helps those migrating from :dalli_store, where an explicit nil was permitted.

    Michael Overmeyer

  • Add Enumerable#in_order_of to put an Enumerable in a certain order by a key.

    DHH

  • ActiveSupport::Inflector.camelize behaves expected when provided a symbol :upper or :lower argument. Matches
    String#camelize behavior.

    Alex Ghiculescu

  • Raises an ArgumentError when the first argument of ActiveSupport::Notification.subscribe is
    invalid.

    Vipul A M

  • HashWithIndifferentAccess#deep_transform_keys now returns a HashWithIndifferentAccess instead of a Hash.

    Nathaniel Woodthorpe

  • Consume dalli’s cache_nils configuration as ActiveSupport::Cache's skip_nil when using MemCacheStore.

    Ritikesh G

  • Add RedisCacheStore#stats method similar to MemCacheStore#stats. Calls redis#info internally.

    Ritikesh G

Guides

  • The autoloading guide for zeitwerk mode has been revised.

    Xavier Noria

  • The autoloading guide for classic mode has been deleted.

    Xavier Noria

Railtie

  • Allow localhost with a port by default in development

    [Fixes: #43864]

  • Remove deprecated config in dbconsole.

    Rafael Mendonça França

  • Change default X-XSS-Protection header to disable XSS auditor

    This header has been deprecated and the XSS auditor it triggered
    has been removed from all major modern browsers (in favour of
    Content Security Policy) that implemented this header to begin with
    (Firefox never did).

    OWASP
    suggests setting this header to '0' to disable the default behaviour
    on old browsers as it can introduce additional security issues.

    Added the new behaviour as a framework default from Rails 7.0.

    Christian Sutter

  • Scaffolds now use date_field, time_field and datetime_field instead of
    date_select, time_select and datetime_select; thus providing native date/time pickers.

    Martijn Lafeber

  • Fix a regression in which autoload paths were initialized too late.

    Xavier Noria

  • Fix activestorage dependency in the npm package.

    Rafael Mendonça França

  • New and upgraded Rails apps no longer generate config/initializers/application_controller_renderer.rb
    or config/initializers/cookies_serializer.rb

    The default value for cookies_serializer (:json) has been moved to config.load_defaults("7.0").
    The new framework defaults file can be used to upgrade the serializer.

    Alex Ghiculescu

  • New applications get a dependency on the new debug gem, replacing byebug.

    Xavier Noria

  • Add SSL support for postgresql in bin/rails dbconsole.

    Fixes #43114.

    Michael Bayucot

  • Add support for comments above gem declaration in Rails application templates, e.g. gem("nokogiri", comment: "For XML").

    Linas Juškevičius

  • The setter config.autoloader= has been deleted. zeitwerk is the only
    available autoloading mode.

    Xavier Noria

  • config.autoload_once_paths can be configured in the body of the
    application class defined in config/application.rb or in the configuration
    for environments in config/environments/*.

    Similarly, engines can configure that collection in the class body of the
    engine class or in the configuration for environments.

    After that, the collection is frozen, and you can autoload from those paths.
    They are managed by the Rails.autoloaders.once autoloader, which does not
    reload, only autoloads/eager loads.

    Xavier Noria

  • During initialization, you cannot autoload reloadable classes or modules
    like application models, unless they are wrapped in a to_prepare block.
    For example, from config/initializers/*, or in application, engines, or
    railties initializers.

    Please check the autoloading
    guide

    for details.

    Xavier Noria

  • While they are allowed to have elements in common, it is no longer required
    that config.autoload_once_paths is a subset of config.autoload_paths.
    The former are managed by the once autoloader. The main autoloader
    manages the latter minus the former.

    Xavier Noria

  • Show Rake task description if command is run with -h.

    Adding -h (or --help) to a Rails command that's a Rake task now outputs
    the task description instead of the general Rake help.

    Petrik de Heus

  • Add missing plugin new command to help.

    *Petrik de Heus

  • Fix config_for error when there's only a shared root array.

    Loïc Delmaire

  • Raise an error in generators if an index type is invalid.

    Petrik de Heus

  • package.json now uses a strict version constraint for Rails JavaScript packages on new Rails apps.

    Zachary Scott, Alex Ghiculescu

  • Modified scaffold generator template so that running
    rails g scaffold Author no longer generates tests called "creating
    a Author", "updating a Author", and "destroying a Author".

    Fixes #40744.

    Michael Duchemin

  • Raise an error in generators if a field type is invalid.

    Petrik de Heus

  • bin/rails tmp:clear deletes also files and directories in tmp/storage.

    George Claghorn

  • Fix compatibility with psych >= 4.

    Starting in Psych 4.0.0 YAML.load behaves like YAML.safe_load. To preserve compatibility
    Rails.application.config_for now uses YAML.unsafe_load if available.

    Jean Boussier

  • Allow loading nested locales in engines.

    Gannon McGibbon

  • Ensure Rails.application.config_for always cast hashes to ActiveSupport::OrderedOptions.

    Jean Boussier

  • Remove Rack::Runtime from the default middleware stack and deprecate
    referencing it in middleware operations without adding it back.

    Hartley McGuire

  • Allow adding additional authorized hosts in development via ENV['RAILS_DEVELOPMENT_HOSTS'].

    Josh Abernathy, Debbie Milburn

  • Add app concern and test keepfiles to generated engine plugins.

    Gannon McGibbon

  • Stop generating a license for in-app plugins.

    Gannon McGibbon

  • rails app:update no longer prompts you to overwrite files that are generally modified in the
    course of developing a Rails app. See #41083 for
    the full list of changes.

    Alex Ghiculescu

  • Change default branch for new Rails projects and plugins to main.

    Prateek Choudhary

  • The new method Rails.benchmark gives you a quick way to measure and log the execution time taken by a block:

    def test_expensive_stuff
      Rails.benchmark("test_expensive_stuff") { ... }
    end
    

    This functionality was available in some contexts only before.

    Simon Perepelitsa

  • Applications generated with --skip-sprockets no longer get app/assets/config/manifest.js and app/assets/stylesheets/application.css.

    Cindy Gao

  • Add support for stylesheets and ERB views to rails stats.

    Joel Hawksley

  • Allow appended root routes to take precedence over internal welcome controller.

    Gannon McGibbon

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 7.0.0.rc3

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • Allow localhost with a port by default in development

    [Fixes: #43864]

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 7.0.0.rc2

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix X_FORWARDED_HOST protection. [CVE-2021-44528]

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.1.4.4

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix issue with host protection not allowing host with port in development.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.1.4.3

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • Allow localhost with a port by default in development

    [Fixes: #43864]

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.1.4.2

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix X_FORWARDED_HOST protection. [CVE-2021-44528]

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.0.4.4

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix issue with host protection not allowing host with port in development.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.0.4.3

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix issue with host protection not allowing localhost in development.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • Allow localhost with a port by default in development

    [Fixes: #43864]

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.0.4.2

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix X_FORWARDED_HOST protection. [CVE-2021-44528]

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 7.0.0.rc1

Active Support

  • Deprecate passing a format to #to_s in favor of #to_formatted_s in Array, Range, Date, DateTime, Time,
    BigDecimal, Float and, Integer.

    Rafael Mendonça França

  • Document ActiveSupport::Testing::Deprecation.

    Sam Bostock & Sam Jordan

  • Add Pathname#existence.

    Pathname.new("file").existence&.read
    

    Timo Schilling

  • Remove deprecate ActiveSupport::Multibyte::Unicode.default_normalization_form.

    Rafael Mendonça França

  • Remove deprecated support to use Range#include? to check the inclusion of a value in
    a date time range is deprecated.

    Rafael Mendonça França

  • Remove deprecated URI.parser.

    Rafael Mendonça França

  • Remove deprecated config.active_support.use_sha1_digests.

    Rafael Mendonça França

  • Invoking Object#with_options without a &block argument returns the
    ActiveSupport::OptionMerger instance.

    Sean Doyle

  • Rails.application.executor hooks can now be called around every test

    This helps to better simulate request or job local state being reset around tests and prevents state
    leaking from one test to another.

    However it requires the executor hooks executed in the test environment to be re-entrant.

    To enable this, set config.active_support.executor_around_test_case = true (this is the default in Rails 7).

    Jean Boussier

  • ActiveSupport::DescendantsTracker now mostly delegate to Class#descendants on Ruby 3.1

    Ruby now provides a fast Class#descendants making ActiveSupport::DescendantsTracker mostly useless.

    As a result the following methods are deprecated:

    • ActiveSupport::DescendantsTracker.direct_descendants
    • ActiveSupport::DescendantsTracker#direct_descendants

    Jean Boussier

  • Fix the Digest::UUID.uuid_from_hash behavior for namespace IDs that are different from the ones defined on Digest::UUID.

    The new behavior will be enabled by setting the
    config.active_support.use_rfc4122_namespaced_uuids option to true
    and is the default for new apps.

    The old behavior is the default for upgraded apps and will output a
    deprecation warning every time a value that is different than one of
    the constants defined on the Digest::UUID extension is used as the
    namespace ID.

    Alex Robbin, Erich Soares Machado, Eugene Kenny

  • ActiveSupport::Inflector::Inflections#clear(:acronyms) is now supported,
    and inflector.clear / inflector.clear(:all) also clears acronyms.

    Alex Ghiculescu, Oliver Peate

Active Model

  • Remove support to Marshal load Rails 5.x ActiveModel::AttributeSet format.

    Rafael Mendonça França

  • Remove support to Marshal and YAML load Rails 5.x error format.

    Rafael Mendonça França

  • Remove deprecated support to use []= in ActiveModel::Errors#messages.

    Rafael Mendonça França

  • Remove deprecated support to delete errors from ActiveModel::Errors#messages.

    Rafael Mendonça França

  • Remove deprecated support to clear errors from ActiveModel::Errors#messages.

    Rafael Mendonça França

  • Remove deprecated support concat errors to ActiveModel::Errors#messages.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#to_xml.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#keys.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#values.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#slice!.

    Rafael Mendonça França

  • Remove deprecated ActiveModel::Errors#to_h.

    Rafael Mendonça França

  • Remove deprecated enumeration of ActiveModel::Errors instances as a Hash.

    Rafael Mendonça França

  • Clear secure password cache if password is set to nil

    Before:

    user.password = 'something'
    user.password = nil

    user.password # => 'something'

    Now:

    user.password = 'something'
    user.password = nil

    user.password # => nil

    Markus Doits

Active Record

  • Remove deprecated ActiveRecord::DatabaseConfigurations::DatabaseConfig#spec_name.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Connection#in_clause_length.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Connection#allowed_index_name_length.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base#remove_connection.

    Rafael Mendonça França

  • Load STI Models in fixtures

    Data from Fixtures now loads based on the specific class for models with
    Single Table Inheritance. This affects enums defined in subclasses, previously
    the value of these fields was not parsed and remained nil

    Andres Howard

  • #authenticate returns false when the password is blank instead of raising an error.

    Muhammad Muhammad Ibrahim

  • Fix ActiveRecord::QueryMethods#in_order_of behavior for integer enums.

    ActiveRecord::QueryMethods#in_order_of didn't work as expected for enums stored as integers in the database when passing an array of strings or symbols as the order argument. This unexpected behavior occurred because the string or symbol values were not casted to match the integers in the database.

    The following example now works as expected:

    class Book < ApplicationRecord
      enum status: [:proposed, :written, :published]
    end
    
    Book.in_order_of(:status, %w[written published proposed])
    

    Alexandre Ruban

  • Ignore persisted in-memory records when merging target lists.

    Kevin Sjöberg

  • Add a new option :update_only to upsert_all to configure the list of columns to update in case of conflict.

    Before, you could only customize the update SQL sentence via :on_duplicate. There is now a new option :update_only that lets you provide a list of columns to update in case of conflict:

    Commodity.upsert_all(
      [
        { id: 2, name: "Copper", price: 4.84 },
        { id: 4, name: "Gold", price: 1380.87 },
        { id: 6, name: "Aluminium", price: 0.35 }
      ],
      update_only: [:price] # Only prices will be updated
    )
    

    Jorge Manrubia

  • Remove deprecated ActiveRecord::Result#map! and ActiveRecord::Result#collect!.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.configurations.to_h.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.configurations.default_hash.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.arel_attribute.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.connection_config.

    Rafael Mendonça França

  • Filter attributes in SQL logs

    Previously, SQL queries in logs containing ActiveRecord::Base.filter_attributes were not filtered.

    Now, the filter attributes will be masked [FILTERED] in the logs when prepared_statement is enabled.

    # Before:
      Foo Load (0.2ms)  SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ?  [["passw", "hello"], ["LIMIT", 1]]
    
    # After:
      Foo Load (0.5ms)  SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ?  [["passw", "[FILTERED]"], ["LIMIT", 1]]
    

    Aishwarya Subramanian

  • Remove deprecated Tasks::DatabaseTasks.spec.

    Rafael Mendonça França

  • Remove deprecated Tasks::DatabaseTasks.current_config.

    Rafael Mendonça França

  • Deprecate Tasks::DatabaseTasks.schema_file_type.

    Rafael Mendonça França

  • Remove deprecated Tasks::DatabaseTasks.dump_filename.

    Rafael Mendonça França

  • Remove deprecated Tasks::DatabaseTasks.schema_file.

    Rafael Mendonça França

  • Remove deprecated environment and name arguments from Tasks::DatabaseTasks.schema_up_to_date?.

    Rafael Mendonça França

  • Merging conditions on the same column no longer maintain both conditions,
    and will be consistently replaced by the latter condition.

    # Rails 6.1 (IN clause is replaced by merger side equality condition)
    Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
    # Rails 6.1 (both conflict conditions exists, deprecated)
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
    # Rails 6.1 with rewhere to migrate to Rails 7.0's behavior
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
    # Rails 7.0 (same behavior with IN clause, mergee side condition is consistently replaced)
    Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
    
    *Rafael Mendonça França*
    
    
  • Remove deprecated support to Model.reorder(nil).first to search using non-deterministic order.

    Rafael Mendonça França

  • Remove deprecated rake tasks:

    • db:schema:load_if_ruby
    • db:structure:dump
    • db:structure:load
    • db:structure:load_if_sql
    • db:structure:dump:#{name}
    • db:structure:load:#{name}
    • db:test:load_structure
    • db:test:load_structure:#{name}

    Rafael Mendonça França

  • Remove deprecated DatabaseConfig#config method.

    Rafael Mendonça França

  • Rollback transactions when the block returns earlier than expected.

    Before this change, when a transaction block returned early, the transaction would be committed.

    The problem is that timeouts triggered inside the transaction block was also making the incomplete transaction
    to be committed, so in order to avoid this mistake, the transaction block is rolled back.

    Rafael Mendonça França

  • Add middleware for automatic shard swapping.

    Provides a basic middleware to perform automatic shard swapping. Applications will provide a resolver which will determine for an individual request which shard should be used. Example:

    config.active_record.shard_resolver = ->(request) {
      subdomain = request.subdomain
      tenant = Tenant.find_by_subdomain!(subdomain)
      tenant.shard
    }
    

    See guides for more details.

    Eileen M. Uchitelle, John Crepezzi

  • Remove deprecated support to pass a column to type_cast.

    Rafael Mendonça França

  • Remove deprecated support to type cast to database values ActiveRecord::Base objects.

    Rafael Mendonça França

  • Remove deprecated support to quote ActiveRecord::Base objects.

    Rafael Mendonça França

  • Remove deprecacated support to resolve connection using "primary" as connection specification name.

    Rafael Mendonça França

  • Remove deprecation warning when using :interval column is used in PostgreSQL database.

    Now, interval columns will return ActiveSupport::Duration objects instead of strings.

    To keep the old behavior, you can add this line to your model:

    attribute :column, :string
    

    Rafael Mendonça França

  • Remove deprecated support to YAML load ActiveRecord::Base instance in the Rails 4.2 and 4.1 formats.

    Rafael Mendonça França

  • Remove deprecated option :spec_name in the configs_for method.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base.allow_unsafe_raw_sql.

    Rafael Mendonça França

  • Fix regression bug that caused ignoring additional conditions for preloading has_many-through relations.

    Fixes #43132

    Alexander Pauly

  • Fix has_many inversing recursion on models with recursive associations.

    Gannon McGibbon

  • Add accepts_nested_attributes_for support for delegated_type

    class Entry < ApplicationRecord
      delegated_type :entryable, types: %w[ Message Comment ]
      accepts_nested_attributes_for :entryable
    end
    
    entry = Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
    # => #<Entry:0x00>
    # id: 1
    # entryable_id: 1,
    # entryable_type: 'Message'
    # ...>
    
    entry.entryable
    # => #<Message:0x01>
    # id: 1
    # content: 'Hello world'
    # ...>
    

    Previously it would raise an error:

    Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' })
    # ArgumentError: Cannot build association `entryable'. Are you trying to build a polymorphic one-to-one association?
    

    Sjors Baltus

  • Use subquery for DELETE with GROUP_BY and HAVING clauses.

    Prior to this change, deletes with GROUP_BY and HAVING were returning an error.

    After this change, GROUP_BY and HAVING are valid clauses in DELETE queries, generating the following query:

    DELETE FROM "posts" WHERE "posts"."id" IN (
        SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" GROUP BY "posts"."id" HAVING (count(comments.id) >= 2))
    )  [["flagged", "t"]]
    

    Ignacio Chiazzo Cardarello

  • Use subquery for UPDATE with GROUP_BY and HAVING clauses.

    Prior to this change, updates with GROUP_BY and HAVING were being ignored, generating a SQL like this:

    UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
        SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
    )  [["flagged", "t"]]
    

    After this change, GROUP_BY and HAVING clauses are used as a subquery in updates, like this:

    UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN (
        SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
        GROUP BY posts.id HAVING (count(comments.id) >= 2)
    )  [["flagged", "t"]]
    

    Ignacio Chiazzo Cardarello

  • Add support for setting the filename of the schema or structure dump in the database config.

    Applications may now set their the filename or path of the schema / structure dump file in their database configuration.

    production:
      primary:
        database: my_db
        schema_dump: my_schema_dump_filename.rb
      animals:
        database: animals_db
        schema_dump: false
    

    The filename set in schema_dump will be used by the application. If set to false the schema will not be dumped. The database tasks are responsible for adding the database directory to the filename. If a full path is provided, the Rails tasks will use that instead of ActiveRecord::DatabaseTasks.db_dir.

    Eileen M. Uchitelle, Ryan Kerr

  • Add ActiveRecord::Base.prohibit_shard_swapping to prevent attempts to change the shard within a block.

    John Crepezzi, Eileen M. Uchitelle

  • Filter unchanged attributes with default function from insert query when partial_inserts is disabled.

    Akshay Birajdar, Jacopo Beschi

  • Add support for FILTER clause (SQL:2003) to Arel.

    Currently supported by PostgreSQL 9.4+ and SQLite 3.30+.

    Andrey Novikov

  • Automatically set timestamps on record creation during bulk insert/upsert

    Prior to this change, only updates during an upsert operation (e.g. upsert_all) would touch timestamps (updated_{at,on}). Now, record creations also touch timestamp columns ({created,updated}_{at,on}).

    This behaviour is controlled by the <model>.record_timestamps config, matching the behaviour of create, update, etc. It can also be overridden by using the record_timestamps: keyword argument.

    Note that this means upsert_all on models with record_timestamps = false will no longer touch updated_{at,on} automatically.

    Sam Bostock

  • Don't require role when passing shard to connected_to.

    connected_to can now be called with a shard only. Note that role is still inherited if connected_to calls are nested.

    Eileen M. Uchitelle

  • Add option to lazily load the schema cache on the connection.

    Previously, the only way to load the schema cache in Active Record was through the Railtie on boot. This option provides the ability to load the schema cache on the connection after it's been established. Loading the cache lazily on the connection can be beneficial for Rails applications that use multiple databases because it will load the cache at the time the connection is established. Currently Railties doesn't have access to the connections before boot.

    To use the cache, set config.active_record.lazily_load_schema_cache = true in your application configuration. In addition a schema_cache_path should be set in your database configuration if you don't want to use the default "db/schema_cache.yml" path.

    Eileen M. Uchitelle

  • Allow automatic inverse_of detection for associations with scopes.

    Automatic inverse_of detection now works for associations with scopes. For
    example, the comments association here now automatically detects
    inverse_of: :post, so we don't need to pass that option:

    class Post < ActiveRecord::Base
      has_many :comments, -> { visible }
    end
    
    class Comment < ActiveRecord::Base
      belongs_to :post
    end
    

    Note that the automatic detection still won't work if the inverse
    association has a scope. In this example a scope on the post association
    would still prevent Rails from finding the inverse for the comments
    association.

    This will be the default for new apps in Rails 7. To opt in:

    config.active_record.automatic_scope_inversing = true
    

    Daniel Colson, Chris Bloom

  • Accept optional transaction args to ActiveRecord::Locking::Pessimistic#with_lock

    #with_lock now accepts transaction options like requires_new:,
    isolation:, and joinable:

  • Adds support for deferrable foreign key constraints in PostgreSQL.

    By default, foreign key constraints in PostgreSQL are checked after each statement. This works for most use cases,
    but becomes a major limitation when creating related records before the parent record is inserted into the database.
    One example of this is looking up / creating a person via one or more unique alias.

    Person.transaction do
      alias = Alias
        .create_with(user_id: SecureRandom.uuid)
        .create_or_find_by(name: "DHH")
    
      person = Person
        .create_with(name: "David Heinemeier Hansson")
        .create_or_find_by(id: alias.user_id)
    end
    

    Using the default behavior, the transaction would fail when executing the first INSERT statement.

    By passing the :deferrable option to the add_foreign_key statement in migrations, it's possible to defer this
    check.

    add_foreign_key :aliases, :person, deferrable: true
    

    Passing deferrable: true doesn't change the default behavior, but allows manually deferring the check using
    SET CONSTRAINTS ALL DEFERRED within a transaction. This will cause the foreign keys to be checked after the
    transaction.

    It's also possible to adjust the default behavior from an immediate check (after the statement), to a deferred check
    (after the transaction):

    add_foreign_key :aliases, :person, deferrable: :deferred
    

    Benedikt Deicke

  • Allow configuring Postgres password through the socket URL.

    For example:

    ActiveRecord::DatabaseConfigurations::UrlConfig.new(
      :production, :production, 'postgres:///?user=user&password=secret&dbname=app', {}
    ).configuration_hash
    

    will now return,

    { :user=>"user", :password=>"secret", :dbname=>"app", :adapter=>"postgresql" }
    

    Abeid Ahmed

  • PostgreSQL: support custom enum types

    In migrations, use create_enum to add a new enum type, and t.enum to add a column.

    def up
      create_enum :mood, ["happy", "sad"]
    
      change_table :cats do |t|
        t.enum :current_mood, enum_type: "mood", default: "happy", null: false
      end
    end
    

    Enums will be presented correctly in schema.rb. Note that this is only supported by
    the PostgreSQL adapter.

    Alex Ghiculescu

  • Avoid COMMENT statements in PostgreSQL structure dumps

    COMMENT statements are now omitted from the output of db:structure:dump when using PostgreSQL >= 11.
    This allows loading the dump without a pgsql superuser account.

    Fixes #36816, #43107.

    Janosch Müller

  • Add support for generated columns in PostgreSQL adapter

    Generated columns are supported since version 12.0 of PostgreSQL. This adds
    support of those to the PostgreSQL adapter.

    create_table :users do |t|
      t.string :name
      t.virtual :name_upcased, type: :string, as: 'upper(name)', stored: true
    end
    

    Michał Begejowicz

Action View

  • Support fields model: [@nested, @model] the same way as form_with model: [@nested, @model].

    Sean Doyle

  • Infer HTTP verb [method] from a model or Array with model as the first
    argument to button_to when combined with a block:

    button_to(Workshop.find(1)){ "Update" }
    #=> <form method="post" action="/workshops/1" class="button_to">
    #=>   <input type="hidden" name="_method" value="patch" autocomplete="off" />
    #=>   <button type="submit">Update</button>
    #=> </form>
    
    button_to([ Workshop.find(1), Session.find(1) ]) { "Update" }
    #=> <form method="post" action="/workshops/1/sessions/1" class="button_to">
    #=>   <input type="hidden" name="_method" value="patch" autocomplete="off" />
    #=>   <button type="submit">Update</button>
    #=> </form>
    

    Sean Doyle

  • Support passing a Symbol as the first argument to FormBuilder#button:

    form.button(:draft, value: true)
    # => <button name="post[draft]" value="true" type="submit">Create post</button>
    
    form.button(:draft, value: true) do
      content_tag(:strong, "Save as draft")
    end
    # =>  <button name="post[draft]" value="true" type="submit">
    #       <strong>Save as draft</strong>
    #     </button>
    

    Sean Doyle

  • Introduce the field_name view helper, along with the
    FormBuilder#field_name counterpart:

    form_for @post do |f|
      f.field_tag :tag, name: f.field_name(:tag, multiple: true)
      # => <input type="text" name="post[tag][]">
    end
    

    Sean Doyle

  • Execute the ActionView::Base.field_error_proc within the context of the
    ActionView::Base instance:

    config.action_view.field_error_proc = proc { |html| content_tag(:div, html, class: "field_with_errors") }
    

    Sean Doyle

  • Add support for button_to ..., authenticity_token: false

    button_to "Create", Post.new, authenticity_token: false
    # => <form class="button_to" method="post" action="/posts"><button type="submit">Create</button></form>
    
    button_to "Create", Post.new, authenticity_token: true
    # => <form class="button_to" method="post" action="/posts"><button type="submit">Create</button><input type="hidden" name="form_token" value="abc123..." autocomplete="off" /></form>
    
    button_to "Create", Post.new, authenticity_token: "secret"
    # => <form class="button_to" method="post" action="/posts"><button type="submit">Create</button><input type="hidden" name="form_token" value="secret" autocomplete="off" /></form>
    

    Sean Doyle

  • Support rendering <form> elements without [action] attributes by:

    • form_with url: false or form_with ..., html: { action: false }
    • form_for ..., url: false or form_for ..., html: { action: false }
    • form_tag false or form_tag ..., action: false
    • button_to "...", false or button_to(false) { ... }

    Sean Doyle

  • Add :day_format option to date_select

    date_select("article", "written_on", day_format: ->(day) { day.ordinalize })
    # generates day options like <option value="1">1st</option>\n<option value="2">2nd</option>...
    

    Shunichi Ikegami

  • Allow link_to helper to infer link name from Model#to_s when it
    is used with a single argument:

    link_to @profile
    #=> <a href="/profiles/1">Eileen</a>
    

    This assumes the model class implements a to_s method like this:

    class Profile < ApplicationRecord
      # ...
      def to_s
        name
      end
    end
    

    Previously you had to supply a second argument even if the Profile
    model implemented a #to_s method that called the name method.

    link_to @profile, @profile.name
    #=> <a href="/profiles/1">Eileen</a>
    

    Olivier Lacan

  • Support svg unpaired tags for tag helper.

    tag.svg { tag.use('href' => "#cool-icon") }
    # => <svg><use href="#cool-icon"></svg>
    

    Oleksii Vasyliev

Action Pack

  • Rails.application.executor hooks can now be called around every request in a ActionController::TestCase

    This helps to better simulate request or job local state being reset between requests and prevent state
    leaking from one request to another.

    To enable this, set config.active_support.executor_around_test_case = true (this is the default in Rails 7).

    Alex Ghiculescu

  • Consider onion services secure for cookies.

    Justin Tracey

  • Remove deprecated Rails.config.action_view.raise_on_missing_translations.

    Rafael Mendonça França

  • Remove deprecated support to passing a path to fixture_file_upload relative to fixture_path.

    Rafael Mendonça França

  • Remove deprecated ActionDispatch::SystemTestCase#host!.

    Rafael Mendonça França

  • Remove deprecated Rails.config.action_dispatch.hosts_response_app.

    Rafael Mendonça França

  • Remove deprecated ActionDispatch::Response.return_only_media_type_on_content_type.

    Rafael Mendonça França

  • Raise ActionController::Redirecting::UnsafeRedirectError for unsafe redirect_to redirects.

    This allows rescue_from to be used to add a default fallback route:

    rescue_from ActionController::Redirecting::UnsafeRedirectError do
      redirect_to root_url
    end
    

    Kasper Timm Hansen, Chris Oliver

  • Add url_from to verify a redirect location is internal.

    Takes the open redirect protection from redirect_to so users can wrap a
    param, and fall back to an alternate redirect URL when the param provided
    one is unsafe.

    def create
      redirect_to url_from(params[:redirect_url]) || root_url
    end
    

    dmcge, Kasper Timm Hansen

  • Allow Capybara driver name overrides in SystemTestCase::driven_by

    Allow users to prevent conflicts among drivers that use the same driver
    type (selenium, poltergeist, webkit, rack test).

    Fixes #42502

    Chris LaRose

  • Allow multiline to be passed in routes when using wildcard segments.

    Previously routes with newlines weren't detected when using wildcard segments, returning
    a No route matches error.
    After this change, routes with newlines are detected on wildcard segments. Example

      draw do
        get "/wildcard/*wildcard_segment", to: SimpleApp.new("foo#index"), as: :wildcard
      end
    
      # After the change, the path matches.
      assert_equal "/wildcard/a%0Anewline", url_helpers.wildcard_path(wildcard_segment: "a\nnewline")
    

    Fixes #39103

    Ignacio Chiazzo

  • Treat html suffix in controller translation.

    Rui Onodera, Gavin Miller

  • Allow permitting numeric params.

    Previously it was impossible to permit different fields on numeric parameters.
    After this change you can specify different fields for each numbered parameter.
    For example params like,

    book: {
            authors_attributes: {
              '0': { name: "William Shakespeare", age_of_death: "52" },
              '1': { name: "Unattributed Assistant" },
              '2': "Not a hash",
              'new_record': { name: "Some name" }
            }
          }
    

    Before you could permit name on each author with,
    permit book: { authors_attributes: [ :name ] }

    After this change you can permit different keys on each numbered element,
    permit book: { authors_attributes: { '1': [ :name ], '0': [ :name, :age_of_death ] } }

    Fixes #41625

    Adam Hess

  • Update HostAuthorization middleware to render debug info only
    when config.consider_all_requests_local is set to true.

    Also, blocked host info is always logged with level error.

    Fixes #42813

    Nikita Vyrko

  • Add Server-Timing middleware

    Server-Timing specification defines how the server can communicate to browsers performance metrics
    about the request it is responding to.

    The ServerTiming middleware is enabled by default on development environment by default using the
    config.server_timing setting and set the relevant duration metrics in the Server-Timing header

    The full specification for Server-Timing header can be found in: https://www.w3.org/TR/server-timing/#dfn-server-timing-header-field

    Sebastian Sogamoso, Guillermo Iguaran

Active Job

  • Remove deprecated :return_false_on_aborted_enqueue option.

    Rafael Mendonça França

  • Deprecated Rails.config.active_job.skip_after_callbacks_if_terminated.

    Rafael Mendonça França

  • Removed deprecated behavior that was not halting after_enqueue/after_perform callbacks when a
    previous callback was halted with throw :abort.

    Rafael Mendonça França

  • Raise an SerializationError in Serializer::ModuleSerializer
    if the module name is not present.

    Veerpal Brar

Action Mailer

  • Remove deprecated ActionMailer::DeliveryJob and ActionMailer::Parameterized::DeliveryJob
    in favor of ActionMailer::MailDeliveryJob.

    Rafael Mendonça França

  • email_address_with_name returns just the address if name is blank.

    Thomas Hutterer

Action Cable

  • The Action Cable client now ensures successful channel subscriptions:

    • The client maintains a set of pending subscriptions until either
      the server confirms the subscription or the channel is torn down.
    • Rectifies the race condition where an unsubscribe is rapidly followed
      by a subscribe (on the same channel identifier) and the requests are
      handled out of order by the ActionCable server, thereby ignoring the
      subscribe command.

    Daniel Spinosa

Active Storage

  • Add ActiveStorage::Blob.compose to concatenate multiple blobs.

    Gannon McGibbon

  • Setting custom metadata on blobs are now persisted to remote storage.

    joshuamsager

  • Support direct uploads to multiple services.

    Dmitry Tsepelev

  • Invalid default content types are deprecated

    Blobs created with content_type image/jpg, image/pjpeg, image/bmp, text/javascript will now produce
    a deprecation warning, since these are not valid content types.

    These content types will be removed from the defaults in Rails 7.1.

    You can set config.active_storage.silence_invalid_content_types_warning = true to dismiss the warning.

    Alex Ghiculescu

Action Mailbox

  • Removed deprecated environment variable MAILGUN_INGRESS_API_KEY.

    Rafael Mendonça França

  • Removed deprecated Rails.application.credentials.action_mailbox.mailgun_api_key.

    Rafael Mendonça França

Action Text

  • Fix an issue with how nested lists were displayed when converting to plain text

    Matt Swanson

  • Allow passing in a custom direct_upload_url or blob_url_template to rich_text_area_tag.

    Lucas Mansur

Railties

  • Remove deprecated config in dbconsole.

    Rafael Mendonça França

  • Change default X-XSS-Protection header to disable XSS auditor

    This header has been deprecated and the XSS auditor it triggered
    has been removed from all major modern browsers (in favour of
    Content Security Policy) that implemented this header to begin with
    (Firefox never did).

    OWASP
    suggests setting this header to '0' to disable the default behaviour
    on old browsers as it can introduce additional security issues.

    Added the new behaviour as a framework default from Rails 7.0.

    Christian Sutter

  • Scaffolds now use date_field, time_field and datetime_field instead of
    date_select, time_select and datetime_select; thus providing native date/time pickers.

    Martijn Lafeber

  • Fix a regression in which autoload paths were initialized too late.

    Xavier Noria

- Ruby
Published by rafaelfranca over 4 years ago

https://github.com/rails/rails - 6.1.4

Active Support

  • MemCacheStore: convert any underlying value (including false) to an Entry.

    See #42559.

    Alex Ghiculescu

  • Fix bug in number_with_precision when using large BigDecimal values.

    Fixes #42302.

    Federico Aldunate, Zachary Scott

  • Check byte size instead of length on secure_compare.

    Tietew

  • Fix Time.at to not lose :in option.

    Ryuta Kamizono

  • Require a path for config.cache_store = :file_store.

    Alex Ghiculescu

  • Avoid having to store complex object in the default translation file.

    Rafael Mendonça França

Active Model

  • Fix to_json for ActiveModel::Dirty object.

    Exclude +mutations_from_database+ attribute from json as it lead to recursion.

    Anil Maurya

Active Record

  • Do not try to rollback transactions that failed due to a ActiveRecord::TransactionRollbackError.

    Jamie McCarthy

  • Raise an error if pool_config is nil in set_pool_config.

    Eileen M. Uchitelle

  • Fix compatibility with psych >= 4.

    Starting in Psych 4.0.0 YAML.load behaves like YAML.safe_load. To preserve compatibility
    Active Record's schema cache loader and YAMLColumn now uses YAML.unsafe_load if available.

    Jean Boussier

  • Support using replicas when using rails dbconsole.

    Christopher Thornton

  • Restore connection pools after transactional tests.

    Eugene Kenny

  • Change upsert_all to fails cleanly for MySQL when :unique_by is used.

    Bastian Bartmann

  • Fix user-defined self.default_scope to respect table alias.

    Ryuta Kamizono

  • Clear @cache_keys cache after update_all, delete_all, destroy_all.

    Ryuta Kamizono

  • Changed Arel predications contains and overlaps to use
    quoted_node so that PostgreSQL arrays are quoted properly.

    Bradley Priest

  • Fix merge when the where clauses have string contents.

    Ryuta Kamizono

  • Fix rollback of parent destruction with nested dependent: :destroy.

    Jacopo Beschi

  • Fix binds logging for "WHERE ... IN ..." statements.

    Ricardo Díaz

  • Handle false in relation strict loading checks.

    Previously when a model had strict loading set to true and then had a
    relation set strict_loading to false the false wasn't considered when
    deciding whether to raise/warn about strict loading.

    class Dog < ActiveRecord::Base
      self.strict_loading_by_default = true
    
      has_many :treats, strict_loading: false
    end
    

    In the example, dog.treats would still raise even though
    strict_loading was set to false. This is a bug effecting more than
    Active Storage which is why I made this PR superceeding #41461. We need
    to fix this for all applications since the behavior is a little
    surprising. I took the test from ##41461 and the code suggestion from #41453
    with some additions.

    Eileen M. Uchitelle, Radamés Roriz

  • Fix numericality validator without precision.

    Ryuta Kamizono

  • Fix aggregate attribute on Enum types.

    Ryuta Kamizono

  • Fix CREATE INDEX statement generation for PostgreSQL.

    eltongo

  • Fix where clause on enum attribute when providing array of strings.

    Ryuta Kamizono

  • Fix unprepared_statement to work it when nesting.

    Ryuta Kamizono

Action View

  • The translate helper now passes default values that aren't
    translation keys through I18n.translate for interpolation.

    Jonathan Hefner

  • Don't attach UJS form submission handlers to Turbo forms.

    David Heinemeier Hansson

  • Allow both current_page?(url_hash) and current_page?(**url_hash) on Ruby 2.7.

    Ryuta Kamizono

Action Pack

  • Ignore file fixtures on db:fixtures:load

    Kevin Sjöberg

  • Fix ActionController::Live controller test deadlocks by removing the body buffer size limit for tests.

    Dylan Thacker-Smith

  • Correctly place optional path parameter booleans.

    Previously, if you specify a url parameter that is part of the path as false it would include that part
    of the path as parameter for example:

    get "(/optional/:optional_id)/things" => "foo#foo", as: :things
    things_path(optional_id: false) # => /things?optional_id=false
    

    After this change, true and false will be treated the same when used as optional path parameters. Meaning now:

    get '(this/:my_bool)/that' as: :that
    
    that_path(my_bool: true) # => `/this/true/that`
    that_path(my_bool: false) # => `/this/false/that`
    

    Adam Hess

  • Add support for 'private, no-store' Cache-Control headers.

    Previously, 'no-store' was exclusive; no other directives could be specified.

    Alex Smith

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • Fix ArgumentError with ruby 3.0 on RemoteConnection#disconnect.

    Vladislav

Active Storage

  • The parameters sent to ffmpeg for generating a video preview image are now
    configurable under config.active_storage.video_preview_arguments.

    Brendon Muir

  • Fix Active Storage update task when running in an engine.

    Justin Malčić*

  • Don't raise an error if the mime type is not recognized.

    Fixes #41777.

    Alex Ghiculescu

  • ActiveStorage::PreviewError is raised when a previewer is unable to generate a preview image.

    Alex Robbin

  • respond with 404 given invalid variation key when asking for representations.

    George Claghorn

  • Blob creation shouldn't crash if no service selected.

    Alex Ghiculescu

Action Mailbox

  • No changes.

Action Text

  • Always render attachment partials as HTML with :html format inside trix editor.

    James Brooks

Railties

  • Fix compatibility with psych >= 4.

    Starting in Psych 4.0.0 YAML.load behaves like YAML.safe_load. To preserve compatibility
    Rails.application.config_for now uses YAML.unsafe_load if available.

    Jean Boussier

  • Ensure Rails.application.config_for always cast hashes to ActiveSupport::OrderedOptions.

    Jean Boussier

  • Fix create migration generator with --pretend option.

    euxx

- Ruby
Published by rafaelfranca about 5 years ago

https://github.com/rails/rails - 6.0.4

Active Support

  • Fixed issue in ActiveSupport::Cache::RedisCacheStore not passing options
    to read_multi causing fetch_multi to not work properly.

    Rajesh Sharma

  • with_options copies its options hash again to avoid leaking mutations.

    Fixes #39343.

    Eugene Kenny

Active Model

  • No changes.

Active Record

  • Only warn about negative enums if a positive form that would cause conflicts exists.

    Fixes #39065.

    Alex Ghiculescu

  • Allow the inverse of a has_one association that was previously autosaved to be loaded.

    Fixes #34255.

    Steven Weber

  • Reset statement cache for association if table_name is changed.

    Fixes #36453.

    Ryuta Kamizono

  • Type cast extra select for eager loading.

    Ryuta Kamizono

  • Prevent collection associations from being autosaved multiple times.

    Fixes #39173.

    Eugene Kenny

  • Resolve issue with insert_all unique_by option when used with expression index.

    When the :unique_by option of ActiveRecord::Persistence.insert_all and
    ActiveRecord::Persistence.upsert_all was used with the name of an expression index, an error
    was raised. Adding a guard around the formatting behavior for the :unique_by corrects this.

    Usage:

    create_table :books, id: :integer, force: true do |t|
      t.column :name, :string
      t.index "lower(name)", unique: true
    end
    
    Book.insert_all [{ name: "MyTest" }], unique_by: :index_books_on_lower_name
    

    Fixes #39516.

    Austen Madden

  • Fix preloading for polymorphic association with custom scope.

    Ryuta Kamizono

  • Allow relations with different SQL comments in the or method.

    Takumi Shotoku

  • Resolve conflict between counter cache and optimistic locking.

    Bump an Active Record instance's lock version after updating its counter
    cache. This avoids raising an unnecessary ActiveRecord::StaleObjectError
    upon subsequent transactions by maintaining parity with the corresponding
    database record's lock_version column.

    Fixes #16449.

    Aaron Lipman

  • Fix through association with source/through scope which has joins.

    Ryuta Kamizono

  • Fix through association to respect source scope for includes/preload.

    Ryuta Kamizono

  • Fix eager load with Arel joins to maintain the original joins order.

    Ryuta Kamizono

  • Fix group by count with eager loading + order + limit/offset.

    Ryuta Kamizono

  • Fix left joins order when merging multiple left joins from different associations.

    Ryuta Kamizono

  • Fix index creation to preserve index comment in bulk change table on MySQL.

    Ryuta Kamizono

  • Change remove_foreign_key to not check :validate option if database
    doesn't support the feature.

    Ryuta Kamizono

  • Fix the result of aggregations to maintain duplicated "group by" fields.

    Ryuta Kamizono

  • Do not return duplicated records when using preload.

    Bogdan Gusiev

Action View

  • SanitizeHelper.sanitized_allowed_attributes and SanitizeHelper.sanitized_allowed_tags
    call safe_list_sanitizer's class method

    Fixes #39586

    Taufiq Muhammadi

Action Pack

  • Accept base64_urlsafe CSRF tokens to make forward compatible.

    Base64 strict-encoded CSRF tokens are not inherently websafe, which makes
    them difficult to deal with. For example, the common practice of sending
    the CSRF token to a browser in a client-readable cookie does not work properly
    out of the box: the value has to be url-encoded and decoded to survive transport.

    In Rails 6.1, we generate Base64 urlsafe-encoded CSRF tokens, which are inherently
    safe to transport. Validation accepts both urlsafe tokens, and strict-encoded
    tokens for backwards compatibility.

    In Rails 5.2.5, the CSRF token format is accidentally changed to urlsafe-encoded.
    If you upgrade apps from 5.2.5, set the config urlsafe_csrf_tokens = true.

    Rails.application.config.action_controller.urlsafe_csrf_tokens = true
    

    Scott Blum, Étienne Barrié

  • Signed and encrypted cookies can now store false as their value when
    action_dispatch.use_cookies_with_metadata is enabled.

    Rolandas Barysas

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • The Poppler PDF previewer renders a preview image using the original
    document's crop box rather than its media box, hiding print margins. This
    matches the behavior of the MuPDF previewer.

    Vincent Robert

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • Allow relative paths with trailing slashes to be passed to rails test.

    Eugene Kenny

  • Return a 405 Method Not Allowed response when a request uses an unknown HTTP method.

    Fixes #38998.

    Loren Norman

- Ruby
Published by rafaelfranca about 5 years ago

https://github.com/rails/rails - 6.1.3.2

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Prevent open redirects by correctly escaping the host allow list
    CVE-2021-22903

  • Prevent catastrophic backtracking during mime parsing
    CVE-2021-22902

  • Prevent regex DoS in HTTP token authentication
    CVE-2021-22904

  • Prevent string polymorphic route arguments.

    url_for supports building polymorphic URLs via an array
    of arguments (usually symbols and records). If a developer passes a
    user input array, strings can result in unwanted route helper calls.

    CVE-2021-22885

    Gannon McGibbon

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca about 5 years ago

https://github.com/rails/rails - 6.0.3.7

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Prevent catastrophic backtracking during mime parsing
    CVE-2021-22902

  • Prevent regex DoS in HTTP token authentication
    CVE-2021-22904

  • Prevent string polymorphic route arguments.

    url_for supports building polymorphic URLs via an array
    of arguments (usually symbols and records). If a developer passes a
    user input array, strings can result in unwanted route helper calls.

    CVE-2021-22885

    Gannon McGibbon

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca about 5 years ago

https://github.com/rails/rails - 5.2.6

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Accept base64_urlsafe CSRF tokens to make forward compatible.

    Base64 strict-encoded CSRF tokens are not inherently websafe, which makes
    them difficult to deal with. For example, the common practice of sending
    the CSRF token to a browser in a client-readable cookie does not work properly
    out of the box: the value has to be url-encoded and decoded to survive transport.

    In this version, we generate Base64 urlsafe-encoded CSRF tokens, which are inherently
    safe to transport. Validation accepts both urlsafe tokens, and strict-encoded
    tokens for backwards compatibility.

    How the tokes are encoded is controllr by the action_controller.urlsafe_csrf_tokens
    config.

    In Rails 5.2.5, the CSRF token format was accidentally changed to urlsafe-encoded.

    Atention: If you already upgraded your application to 5.2.5, set the config
    urlsafe_csrf_tokens to true, otherwise your form submission will start to fail
    during the deploy of this new version.

    Rails.application.config.action_controller.urlsafe_csrf_tokens = true
    

    If you are upgrading from 5.2.4.x, you don't need to change this configuration.

    Scott Blum, Étienne Barrié

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca about 5 years ago

https://github.com/rails/rails - 5.2.4.6

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Prevent regex DoS in HTTP token authentication
    CVE-2021-22904

  • Prevent string polymorphic route arguments.

    url_for supports building polymorphic URLs via an array
    of arguments (usually symbols and records). If a developer passes a
    user input array, strings can result in unwanted route helper calls.

    CVE-2021-22885

    Gannon McGibbon

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca about 5 years ago

https://github.com/rails/rails - 6.1.3.1

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • Marcel is upgraded to version 1.0.0 to avoid a dependency on GPL-licensed mime types data.

    George Claghorn

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by georgeclaghorn over 5 years ago

https://github.com/rails/rails - 6.0.3.6

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • Marcel is upgraded to version 1.0.0 to avoid a dependency on GPL-licensed mime types data.

    George Claghorn

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by georgeclaghorn over 5 years ago

https://github.com/rails/rails - 5.2.5

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • Marcel is upgraded to version 1.0.0 to avoid a dependency on GPL-licensed mime types data.

    George Claghorn

Railties

  • No changes.

- Ruby
Published by georgeclaghorn over 5 years ago

https://github.com/rails/rails - 6.1.3

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • Fix the MySQL adapter to always set the right collation and charset
    to the connection session.

    Rafael Mendonça França

  • Fix MySQL adapter handling of time objects when prepared statements
    are enabled.

    Rafael Mendonça França

  • Fix scoping in enum fields using conditions that would generate
    an IN clause.

    Ryuta Kamizono

  • Skip optimised #exist? query when #include? is called on a relation
    with a having clause

    Relations that have aliased select values AND a having clause that
    references an aliased select value would generate an error when
    #include? was called, due to an optimisation that would generate
    call #exists? on the relation instead, which effectively alters
    the select values of the query (and thus removes the aliased select
    values), but leaves the having clause intact. Because the having
    clause is then referencing an aliased column that is no longer
    present in the simplified query, an ActiveRecord::InvalidStatement
    error was raised.

    An sample query affected by this problem:

    Author.select('COUNT(*) as total_posts', 'authors.*')
          .joins(:posts)
          .group(:id)
          .having('total_posts > 2')
          .include?(Author.first)
    

    This change adds an addition check to the condition that skips the
    simplified #exists? query, which simply checks for the presence of
    a having clause.

    Fixes #41417

    Michael Smart

  • Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted
    without Rails knowledge (e.g., if app gets kill -9d during long-running query or due to Rack::Timeout), app won't end
    up in perpetual crash state for being inconsistent with Postgres.

    wbharding, Martin Tepper

Action View

  • No changes.

Action Pack

  • Re-define routes when not set correctly via inheritance.

    John Hawthorn

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 6.1.2.1

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • Fix possible DoS vector in PostgreSQL money type

    Carefully crafted input can cause a DoS via the regular expressions used
    for validating the money format in the PostgreSQL adapter. This patch
    fixes the regexp.

    Thanks to @dee-see from Hackerone for this patch!

    [CVE-2021-22880]

    Aaron Patterson

Action View

  • No changes.

Action Pack

  • Prevent open redirect when allowed host starts with a dot

    [CVE-2021-22881]

    Thanks to @tktech (https://hackerone.com/tktech) for reporting this
    issue and the patch!

    Aaron Patterson

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 6.0.3.5

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • Fix possible DoS vector in PostgreSQL money type

    Carefully crafted input can cause a DoS via the regular expressions used
    for validating the money format in the PostgreSQL adapter. This patch
    fixes the regexp.

    Thanks to @dee-see from Hackerone for this patch!

    [CVE-2021-22880]

    Aaron Patterson

Action View

  • No changes.

Action Pack

  • Prevent open redirect when allowed host starts with a dot

    [CVE-2021-22881]

    Thanks to @tktech (https://hackerone.com/tktech) for reporting this
    issue and the patch!

    Aaron Patterson

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 5.2.4.5

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • Fix possible DoS vector in PostgreSQL money type

    Carefully crafted input can cause a DoS via the regular expressions used
    for validating the money format in the PostgreSQL adapter. This patch
    fixes the regexp.

    Thanks to @dee-see from Hackerone for this patch!

    [CVE-2021-22880]

    Aaron Patterson

Action View

  • No changes.

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 6.1.2

Active Support

  • ActiveSupport::Cache::MemCacheStore now accepts an explicit nil for its addresses argument.

    config.cache_store = :mem_cache_store, nil
    
    # is now equivalent to
    
    config.cache_store = :mem_cache_store
    
    # and is also equivalent to
    
    config.cache_store = :mem_cache_store, ENV["MEMCACHE_SERVERS"] || "localhost:11211"
    
    # which is the fallback behavior of Dalli
    

    This helps those migrating from :dalli_store, where an explicit nil was permitted.

    Michael Overmeyer

Active Model

  • No changes.

Active Record

  • Fix timestamp type for sqlite3.

    Eileen M. Uchitelle

  • Make destroy async transactional.

    An active record rollback could occur while enqueuing a job. In this
    case the job would enqueue even though the database deletion
    rolledback putting things in a funky state.

    Now the jobs are only enqueued until after the db transaction has been committed.

    Cory Gwin

  • Fix malformed packet error in MySQL statement for connection configuration.

    robinroestenburg

  • Connection specification now passes the "url" key as a configuration for the
    adapter if the "url" protocol is "jdbc", "http", or "https". Previously only
    urls with the "jdbc" prefix were passed to the Active Record Adapter, others
    are assumed to be adapter specification urls.

    Fixes #41137.

    Jonathan Bracy

  • Fix granular connection swapping when there are multiple abstract classes.

    Eileen M. Uchitelle

  • Fix find_by with custom primary key for belongs_to association.

    Ryuta Kamizono

  • Add support for rails console --sandbox for multiple database applications.

    alpaca-tc

  • Fix where on polymorphic association with empty array.

    Ryuta Kamizono

  • Fix preventing writes for ApplicationRecord.

    Eileen M. Uchitelle

Action View

  • No changes.

Action Pack

  • Fix error in ActionController::LogSubscriber that would happen when throwing inside a controller action.

    Janko Marohnić

  • Fix fixture_file_upload deprecation when file_fixture_path is a relative path.

    Eugene Kenny

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 6.1.1

Active Support

  • Change IPAddr#to_json to match the behavior of the json gem returning the string representation
    instead of the instance variables of the object.

    Before:

    IPAddr.new("127.0.0.1").to_json
    # => "{\"addr\":2130706433,\"family\":2,\"mask_addr\":4294967295}"
    

    After:

    IPAddr.new("127.0.0.1").to_json
    # => "\"127.0.0.1\""
    

Active Model

  • No changes.

Active Record

  • Fix fixtures loading when strict loading is enabled for the association.

    Alex Ghiculescu

  • Fix where with custom primary key for belongs_to association.

    Ryuta Kamizono

  • Fix where with aliased associations.

    Ryuta Kamizono

  • Fix composed_of with symbol mapping.

    Ryuta Kamizono

  • Don't skip money's type cast for pluck and calculations.

    Ryuta Kamizono

  • Fix where on polymorphic association with non Active Record object.

    Ryuta Kamizono

  • Make sure db:prepare works even the schema file doesn't exist.

    Rafael Mendonça França

  • Fix complicated has_many :through with nested where condition.

    Ryuta Kamizono

  • Handle STI models for has_many dependent: :destroy_async.

    Muhammad Usman

  • Restore possibility of passing false to :polymorphic option of belongs_to.

    Previously, passing false would trigger the option validation logic
    to throw an error saying :polymorphic would not be a valid option.

    glaszig

  • Allow adding nonnamed expression indexes to be revertible.

    Fixes #40732.

    Previously, the following code would raise an error, when executed while rolling back,
    and the index name should be specified explicitly. Now, the index name is inferred
    automatically.

    add_index(:items, "to_tsvector('english', description)")
    

    fatkodima

Action View

  • Fix lazy translation in partial with block.

    Marek Kasztelnik

  • Avoid extra SELECT COUNT queries when rendering Active Record collections.

    aar0nr

  • Link preloading keep integrity hashes in the header.

    Étienne Barrié

  • Add config.action_view.preload_links_header to allow disabling of
    the Link header being added by default when using stylesheet_link_tag
    and javascript_include_tag.

    Andrew White

  • The translate helper now resolves default values when a nil key is
    specified, instead of always returning nil.

    Jonathan Hefner

Action Pack

  • Fix nil translation key lookup in controllers/

    Jan Klimo

  • Quietly handle unknown HTTP methods in Action Dispatch SSL middleware.

    Alex Robbin

  • Change the request method to a GET when passing failed requests down to config.exceptions_app.

    Alex Robbin

Active Job

  • Make retry_job return the job that was created.

    Rafael Mendonça França

  • Include ActiveSupport::Testing::Assertions in ActiveJob::TestHelpers.

    Mikkel Malmberg

Action Mailer

  • Sets default mailer queue to "default" in the mail assertions.

    Paul Keen

Action Cable

  • No changes.

Active Storage

  • Fix S3 multipart uploads when threshold is larger than file.

    Matt Muller

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • Allow spaces in path to Yarn binstub and only run on precompile if needed.

    Markus Doits

  • Populate ARGV for app template.

    Fixes #40945.

    Jonathan Hefner

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 6.1.0

Active Support

  • Ensure MemoryStore disables compression by default. Reverts behavior of
    MemoryStore to its prior rails 5.1 behavior.

    Max Gurewitz

  • Calling iso8601 on negative durations retains the negative sign on individual
    digits instead of prepending it.

    This change is required so we can interoperate with PostgreSQL, which prefers
    negative signs for each component.

    Compatibility with other iso8601 parsers which support leading negatives as well
    as negatives per component is still retained.

    Before:

    (-1.year - 1.day).iso8601
    # => "-P1Y1D"
    

    After:

    (-1.year - 1.day).iso8601
    # => "P-1Y-1D"
    

    Vipul A M

  • Remove deprecated ActiveSupport::Notifications::Instrumenter#end=.

    Rafael Mendonça França

  • Deprecate ActiveSupport::Multibyte::Unicode.default_normalization_form.

    Rafael Mendonça França

  • Remove deprecated ActiveSupport::Multibyte::Unicode.pack_graphemes,
    ActiveSupport::Multibyte::Unicode.unpack_graphemes,
    ActiveSupport::Multibyte::Unicode.normalize,
    ActiveSupport::Multibyte::Unicode.downcase,
    ActiveSupport::Multibyte::Unicode.upcase and ActiveSupport::Multibyte::Unicode.swapcase.

    Rafael Mendonça França

  • Remove deprecated ActiveSupport::Multibyte::Chars#consumes? and ActiveSupport::Multibyte::Chars#normalize.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/range/include_range.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/hash/transform_values.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/hash/compact.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/array/prepend_and_append.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/numeric/inquiry.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/module/reachable.

    Rafael Mendonça França

  • Remove deprecated Module#parent_name, Module#parent and Module#parents.

    Rafael Mendonça França

  • Remove deprecated ActiveSupport::LoggerThreadSafeLevel#after_initialize.

    Rafael Mendonça França

  • Remove deprecated LoggerSilence constant.

    Rafael Mendonça França

  • Remove deprecated fallback to I18n.default_local when config.i18n.fallbacks is empty.

    Rafael Mendonça França

  • Remove entries from local cache on RedisCacheStore#delete_matched

    Fixes #38627

    ojab

  • Speed up ActiveSupport::SecurityUtils.fixed_length_secure_compare by using
    OpenSSL.fixed_length_secure_compare, if available.

    Nate Matykiewicz

  • ActiveSupport::Cache::MemCacheStore now checks ENV["MEMCACHE_SERVERS"] before falling back to "localhost:11211" if configured without any addresses.

    config.cache_store = :mem_cache_store
    
    # is now equivalent to
    
    config.cache_store = :mem_cache_store, ENV["MEMCACHE_SERVERS"] || "localhost:11211"
    
    # instead of
    
    config.cache_store = :mem_cache_store, "localhost:11211" # ignores ENV["MEMCACHE_SERVERS"]
    

    Sam Bostock

  • ActiveSupport::Subscriber#attach_to now accepts an inherit_all: argument. When set to true,
    it allows a subscriber to receive events for methods defined in the subscriber's ancestor class(es).

    class ActionControllerSubscriber < ActiveSupport::Subscriber
      attach_to :action_controller
    
      def start_processing(event)
        info "Processing by #{event.payload[:controller]}##{event.payload[:action]} as #{format}"
      end
    
      def redirect_to(event)
        info { "Redirected to #{event.payload[:location]}" }
      end
    end
    
    # We detach ActionControllerSubscriber from the :action_controller namespace so that our CustomActionControllerSubscriber
    # can provide its own instrumentation for certain events in the namespace
    ActionControllerSubscriber.detach_from(:action_controller)
    
    class CustomActionControllerSubscriber < ActionControllerSubscriber
      attach_to :action_controller, inherit_all: true
    
      def start_processing(event)
        info "A custom response to start_processing events"
      end
    
      # => CustomActionControllerSubscriber will process events for "start_processing.action_controller" notifications
      # using its own #start_processing implementation, while retaining ActionControllerSubscriber's instrumentation
      # for "redirect_to.action_controller" notifications
    end
    

    Adrianna Chang

  • Allow the digest class used to generate non-sensitive digests to be configured with config.active_support.hash_digest_class.

    config.active_support.use_sha1_digests is deprecated in favour of config.active_support.hash_digest_class = ::Digest::SHA1.

    Dirkjan Bussink

  • Fix bug to make memcached write_entry expire correctly with unless_exist

    Jye Lee

  • Add ActiveSupport::Duration conversion methods

    in_seconds, in_minutes, in_hours, in_days, in_weeks, in_months, and in_years return the respective duration covered.

    Jason York

  • Fixed issue in ActiveSupport::Cache::RedisCacheStore not passing options
    to read_multi causing fetch_multi to not work properly

    Rajesh Sharma

  • Fixed issue in ActiveSupport::Cache::MemCacheStore which caused duplicate compression,
    and caused the provided compression_threshold to not be respected.

    Max Gurewitz

  • Prevent RedisCacheStore and MemCacheStore from performing compression
    when reading entries written with raw: true.

    Max Gurewitz

  • URI.parser is deprecated and will be removed in Rails 6.2. Use
    URI::DEFAULT_PARSER instead.

    Jean Boussier

  • require_dependency has been documented to be obsolete in :zeitwerk
    mode. The method is not deprecated as such (yet), but applications are
    encouraged to not use it.

    In :zeitwerk mode, semantics match Ruby's and you do not need to be
    defensive with load order. Just refer to classes and modules normally. If
    the constant name is dynamic, camelize if needed, and constantize.

    Xavier Noria

  • Add 3rd person aliases of Symbol#start_with? and Symbol#end_with?.

    :foo.starts_with?("f") # => true
    :foo.ends_with?("o")   # => true
    

    Ryuta Kamizono

  • Add override of unary plus for ActiveSupport::Duration.

    + 1.second is now identical to +1.second to prevent errors
    where a seemingly innocent change of formatting leads to a change in the code behavior.

    Before:

    +1.second.class
    # => ActiveSupport::Duration
    (+ 1.second).class
    # => Integer
    

    After:

    +1.second.class
    # => ActiveSupport::Duration
    (+ 1.second).class
    # => ActiveSupport::Duration
    

    Fixes #39079.

    Roman Kushnir

  • Add subsec to ActiveSupport::TimeWithZone#inspect.

    Before:

    Time.at(1498099140).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00 UTC +00:00"
    Time.at(1498099140, 123456780, :nsec).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00 UTC +00:00"
    Time.at(1498099140 + Rational("1/3")).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00 UTC +00:00"
    

    After:

    Time.at(1498099140).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00.000000000 UTC +00:00"
    Time.at(1498099140, 123456780, :nsec).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00.123456780 UTC +00:00"
    Time.at(1498099140 + Rational("1/3")).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00.333333333 UTC +00:00"
    

    akinomaeni

  • Calling ActiveSupport::TaggedLogging#tagged without a block now returns a tagged logger.

    logger.tagged("BCX").info("Funky time!") # => [BCX] Funky time!
    

    Eugene Kenny

  • Align Range#cover? extension behavior with Ruby behavior for backwards ranges.

    (1..10).cover?(5..3) now returns false, as it does in plain Ruby.

    Also update #include? and #=== behavior to match.

    Michael Groeneman

  • Update to TZInfo v2.0.0.

    This changes the output of ActiveSupport::TimeZone.utc_to_local, but
    can be controlled with the
    ActiveSupport.utc_to_local_returns_utc_offset_times config.

    New Rails 6.1 apps have it enabled by default, existing apps can upgrade
    via the config in config/initializers/new_framework_defaults_6_1.rb

    See the utc_to_local_returns_utc_offset_times documentation for details.

    Phil Ross, Jared Beck

  • Add Date and Time #yesterday? and #tomorrow? alongside #today?.

    Aliased to #prev_day? and #next_day? to match the existing #prev/next_day methods.

    Jatin Dhankhar

  • Add Enumerable#pick to complement ActiveRecord::Relation#pick.

    Eugene Kenny

  • [Breaking change] ActiveSupport::Callbacks#halted_callback_hook now receive a 2nd argument:

    ActiveSupport::Callbacks#halted_callback_hook now receive the name of the callback
    being halted as second argument.
    This change will allow you to differentiate which callbacks halted the chain
    and act accordingly.

      class Book < ApplicationRecord
        before_save { throw(:abort) }
        before_create { throw(:abort) }
    
        def halted_callback_hook(filter, callback_name)
          Rails.logger.info("Book couldn't be #{callback_name}d")
        end
    
        Book.create # => "Book couldn't be created"
        book.save # => "Book couldn't be saved"
      end
    

    Edouard Chin

  • Support prepend with ActiveSupport::Concern.

    Allows a module with extend ActiveSupport::Concern to be prepended.

    module Imposter
      extend ActiveSupport::Concern
    
      # Same as `included`, except only run when prepended.
      prepended do
      end
    end
    
    class Person
      prepend Imposter
    end
    

    Class methods are prepended to the base class, concerning is also
    updated: concerning :Imposter, prepend: true do.

    Jason Karns, Elia Schito

  • Deprecate using Range#include? method to check the inclusion of a value
    in a date time range. It is recommended to use Range#cover? method
    instead of Range#include? to check the inclusion of a value
    in a date time range.

    Vishal Telangre

  • Support added for a round_mode parameter, in all number helpers. (See: BigDecimal::mode.)

    number_to_currency(1234567890.50, precision: 0, round_mode: :half_down) # => "$1,234,567,890"
    number_to_percentage(302.24398923423, precision: 5, round_mode: :down) # => "302.24398%"
    number_to_rounded(389.32314, precision: 0, round_mode: :ceil) # => "390"
    number_to_human_size(483989, precision: 2, round_mode: :up) # => "480 KB"
    number_to_human(489939, precision: 2, round_mode: :floor) # => "480 Thousand"
    
    485000.to_s(:human, precision: 2, round_mode: :half_even) # => "480 Thousand"
    

    Tom Lord

  • Array#to_sentence no longer returns a frozen string.

    Before:

    ['one', 'two'].to_sentence.frozen?
    # => true
    

    After:

    ['one', 'two'].to_sentence.frozen?
    # => false
    

    Nicolas Dular

  • When an instance of ActiveSupport::Duration is converted to an iso8601 duration string, if weeks are mixed with date parts, the week part will be converted to days.
    This keeps the parser and serializer on the same page.

    duration = ActiveSupport::Duration.build(1000000)
    # 1 week, 4 days, 13 hours, 46 minutes, and 40.0 seconds
    
    duration_iso = duration.iso8601
    # P11DT13H46M40S
    
    ActiveSupport::Duration.parse(duration_iso)
    # 11 days, 13 hours, 46 minutes, and 40 seconds
    
    duration = ActiveSupport::Duration.build(604800)
    # 1 week
    
    duration_iso = duration.iso8601
    # P1W
    
    ActiveSupport::Duration.parse(duration_iso)
    # 1 week
    

    Abhishek Sarkar

  • Add block support to ActiveSupport::Testing::TimeHelpers#travel_back.

    Tim Masliuchenko

  • Update ActiveSupport::Messages::Metadata#fresh? to work for cookies with expiry set when
    ActiveSupport.parse_json_times = true.

    Christian Gregg

  • Support symbolic links for content_path in ActiveSupport::EncryptedFile.

    Takumi Shotoku

  • Improve Range#===, Range#include?, and Range#cover? to work with beginless (startless)
    and endless range targets.

    Allen Hsu, Andrew Hodgkinson

  • Don't use Process#clock_gettime(CLOCK_THREAD_CPUTIME_ID) on Solaris.

    Iain Beeston

  • Prevent ActiveSupport::Duration.build(value) from creating instances of
    ActiveSupport::Duration unless value is of type Numeric.

    Addresses the errant set of behaviours described in #37012 where
    ActiveSupport::Duration comparisons would fail confusingly
    or return unexpected results when comparing durations built from instances of String.

    Before:

    small_duration_from_string = ActiveSupport::Duration.build('9')
    large_duration_from_string = ActiveSupport::Duration.build('100000000000000')
    small_duration_from_int = ActiveSupport::Duration.build(9)
    
    large_duration_from_string > small_duration_from_string
    # => false
    
    small_duration_from_string == small_duration_from_int
    # => false
    
    small_duration_from_int < large_duration_from_string
    # => ArgumentError (comparison of ActiveSupport::Duration::Scalar with ActiveSupport::Duration failed)
    
    large_duration_from_string > small_duration_from_int
    # => ArgumentError (comparison of String with ActiveSupport::Duration failed)
    

    After:

    small_duration_from_string = ActiveSupport::Duration.build('9')
    # => TypeError (can't build an ActiveSupport::Duration from a String)
    

    Alexei Emam

  • Add ActiveSupport::Cache::Store#delete_multi method to delete multiple keys from the cache store.

    Peter Zhu

  • Support multiple arguments in HashWithIndifferentAccess for merge and update methods, to
    follow Ruby 2.6 addition.

    Wojciech Wnętrzak

  • Allow initializing thread_mattr_* attributes via :default option.

    class Scraper
      thread_mattr_reader :client, default: Api::Client.new
    end
    

    Guilherme Mansur

  • Add compact_blank for those times when you want to remove #blank? values from
    an Enumerable (also compact_blank! on Hash, Array, ActionController::Parameters).

    Dana Sherson

  • Make ActiveSupport::Logger Fiber-safe.

    Use Fiber.current.__id__ in ActiveSupport::Logger#local_level= in order
    to make log level local to Ruby Fibers in addition to Threads.

    Example:

    logger = ActiveSupport::Logger.new(STDOUT)
    logger.level = 1
    puts "Main is debug? #{logger.debug?}"
    
    Fiber.new {
      logger.local_level = 0
      puts "Thread is debug? #{logger.debug?}"
    }.resume
    
    puts "Main is debug? #{logger.debug?}"
    

    Before:

    Main is debug? false
    Thread is debug? true
    Main is debug? true
    

    After:

    Main is debug? false
    Thread is debug? true
    Main is debug? false
    

    Fixes #36752.

    Alexander Varnin

  • Allow the on_rotation proc used when decrypting/verifying a message to be
    passed at the constructor level.

    Before:

    crypt = ActiveSupport::MessageEncryptor.new('long_secret')
    crypt.decrypt_and_verify(encrypted_message, on_rotation: proc { ... })
    crypt.decrypt_and_verify(another_encrypted_message, on_rotation: proc { ... })
    

    After:

    crypt = ActiveSupport::MessageEncryptor.new('long_secret', on_rotation: proc { ... })
    crypt.decrypt_and_verify(encrypted_message)
    crypt.decrypt_and_verify(another_encrypted_message)
    

    Edouard Chin

  • delegate_missing_to would raise a DelegationError if the object
    delegated to was nil. Now the allow_nil option has been added to enable
    the user to specify they want nil returned in this case.

    Matthew Tanous

  • truncate would return the original string if it was too short to be truncated
    and a frozen string if it were long enough to be truncated. Now truncate will
    consistently return an unfrozen string regardless. This behavior is consistent
    with gsub and strip.

    Before:

    'foobar'.truncate(5).frozen?
    # => true
    'foobar'.truncate(6).frozen?
    # => false
    

    After:

    'foobar'.truncate(5).frozen?
    # => false
    'foobar'.truncate(6).frozen?
    # => false
    

    Jordan Thomas

Active Model

  • Pass in base instead of base_class to Error.human_attribute_name

    This is useful in cases where the human_attribute_name method depends
    on other attributes' values of the class under validation to derive what the
    attribute name should be.

    Filipe Sabella

  • Deprecate marshalling load from legacy attributes format.

    Ryuta Kamizono

  • *_previously_changed? accepts :from and :to keyword arguments like *_changed?.

    topic.update!(status: :archived)
    topic.status_previously_changed?(from: "active", to: "archived")
    # => true
    

    George Claghorn

  • Raise FrozenError when trying to write attributes that aren't backed by the database on an object that is frozen:

    class Animal
      include ActiveModel::Attributes
      attribute :age
    end
    
    animal = Animal.new
    animal.freeze
    animal.age = 25 # => FrozenError, "can't modify a frozen Animal"
    

    Josh Brody

  • Add *_previously_was attribute methods when dirty tracking. Example:

    pirate.update(catchphrase: "Ahoy!")
    pirate.previous_changes["catchphrase"] # => ["Thar She Blows!", "Ahoy!"]
    pirate.catchphrase_previously_was # => "Thar She Blows!"
    

    DHH

  • Encapsulate each validation error as an Error object.

    The ActiveModel’s errors collection is now an array of these Error
    objects, instead of messages/details hash.

    For each of these Error object, its message and full_message methods
    are for generating error messages. Its details method would return error’s
    extra parameters, found in the original details hash.

    The change tries its best at maintaining backward compatibility, however
    some edge cases won’t be covered, like errors#first will return ActiveModel::Error and manipulating
    errors.messages and errors.details hashes directly will have no effect. Moving forward,
    please convert those direct manipulations to use provided API methods instead.

    The list of deprecated methods and their planned future behavioral changes at the next major release are:

    • errors#slice! will be removed.
    • errors#each with the key, value two-arguments block will stop working, while the error single-argument block would return Error object.
    • errors#values will be removed.
    • errors#keys will be removed.
    • errors#to_xml will be removed.
    • errors#to_h will be removed, and can be replaced with errors#to_hash.
    • Manipulating errors itself as a hash will have no effect (e.g. errors[:foo] = 'bar').
    • Manipulating the hash returned by errors#messages (e.g. errors.messages[:foo] = 'bar') will have no effect.
    • Manipulating the hash returned by errors#details (e.g. errors.details[:foo].clear) will have no effect.

    lulalala

Active Record

  • Only warn about negative enums if a positive form that would cause conflicts exists.

    Fixes #39065.

    Alex Ghiculescu

  • Change attribute_for_inspect to take filter_attributes in consideration.

    Rafael Mendonça França

  • Fix odd behavior of inverse_of with multiple belongs_to to same class.

    Fixes #35204.

    Tomoyuki Kai

  • Build predicate conditions with objects that delegate #id and primary key:

    class AdminAuthor
      delegate_missing_to :@author
    
      def initialize(author)
        @author = author
      end
    end
    
    Post.where(author: AdminAuthor.new(author))
    

    Sean Doyle

  • Add connected_to_many API.

    This API allows applications to connect to multiple databases at once without switching all of them or implementing a deeply nested stack.

    Before:

    AnimalsRecord.connected_to(role: :reading) do
    MealsRecord.connected_to(role: :reading) do
    Dog.first # read from animals replica
    Dinner.first # read from meals replica
    Person.first # read from primary writer
    end
    end

    After:

    ActiveRecord::Base.connected_to_many([AnimalsRecord, MealsRecord], role: :reading) do
    Dog.first # read from animals replica
    Dinner.first # read from meals replica
    Person.first # read from primary writer
    end

    Eileen M. Uchitelle, John Crepezzi

  • Add option to raise or log for ActiveRecord::StrictLoadingViolationError.

    Some applications may not want to raise an error in production if using strict_loading. This would allow an application to set strict loading to log for the production environment while still raising in development and test environments.

    Set config.active_record.action_on_strict_loading_violation to :log errors instead of raising.

    Eileen M. Uchitelle

  • Allow the inverse of a has_one association that was previously autosaved to be loaded.

    Fixes #34255.

    Steven Weber

  • Optimise the length of index names for polymorphic references by using the reference name rather than the type and id column names.

    Because the default behaviour when adding an index with multiple columns is to use all column names in the index name, this could frequently lead to overly long index names for polymorphic references which would fail the migration if it exceeded the database limit.

    This change reduces the chance of that happening by using the reference name, e.g. index_my_table_on_my_reference.

    Fixes #38655.

    Luke Redpath

  • MySQL: Uniqueness validator now respects default database collation,
    no longer enforce case sensitive comparison by default.

    Ryuta Kamizono

  • Remove deprecated methods from ActiveRecord::ConnectionAdapters::DatabaseLimits.

    column_name_length
    table_name_length
    columns_per_table
    indexes_per_table
    columns_per_multicolumn_index
    sql_query_length
    joins_per_query

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_multi_insert?.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_foreign_keys_in_create?.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#supports_ranges?.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base#update_attributes and ActiveRecord::Base#update_attributes!.

    Rafael Mendonça França

  • Remove deprecated migrations_path argument in ActiveRecord::ConnectionAdapter::SchemaStatements#assume_migrated_upto_version.

    Rafael Mendonça França

  • Remove deprecated config.active_record.sqlite3.represent_boolean_as_integer.

    Rafael Mendonça França

  • relation.create does no longer leak scope to class level querying methods
    in initialization block and callbacks.

    Before:

    User.where(name: "John").create do |john|
      User.find_by(name: "David") # => nil
    end
    

    After:

    User.where(name: "John").create do |john|
      User.find_by(name: "David") # => #<User name: "David", ...>
    end
    

    Ryuta Kamizono

  • Named scope chain does no longer leak scope to class level querying methods.

    class User < ActiveRecord::Base
      scope :david, -> { User.where(name: "David") }
    end
    

    Before:

    User.where(name: "John").david
    # SELECT * FROM users WHERE name = 'John' AND name = 'David'
    

    After:

    User.where(name: "John").david
    # SELECT * FROM users WHERE name = 'David'
    

    Ryuta Kamizono

  • Remove deprecated methods from ActiveRecord::DatabaseConfigurations.

    fetch
    each
    first
    values
    []=

    Rafael Mendonça França

  • where.not now generates NAND predicates instead of NOR.

    Before:

     User.where.not(name: "Jon", role: "admin")
     # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
    

    After:

     User.where.not(name: "Jon", role: "admin")
     # SELECT * FROM users WHERE NOT (name == 'Jon' AND role == 'admin')
    

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Result#to_hash method.

    Rafael Mendonça França

  • Deprecate ActiveRecord::Base.allow_unsafe_raw_sql.

    Rafael Mendonça França

  • Remove deprecated support for using unsafe raw SQL in ActiveRecord::Relation methods.

    Rafael Mendonça França

  • Allow users to silence the "Rails couldn't infer whether you are using multiple databases..."
    message using config.active_record.suppress_multiple_database_warning.

    Omri Gabay

  • Connections can be granularly switched for abstract classes when connected_to is called.

    This change allows connected_to to switch a role and/or shard for a single abstract class instead of all classes globally. Applications that want to use the new feature need to set config.active_record.legacy_connection_handling to false in their application configuration.

    Example usage:

    Given an application we have a User model that inherits from ApplicationRecord and a Dog model that inherits from AnimalsRecord. AnimalsRecord and ApplicationRecord have writing and reading connections as well as shard default, one, and two.

    ActiveRecord::Base.connected_to(role: :reading) do
      User.first # reads from default replica
      Dog.first # reads from default replica
    
      AnimalsRecord.connected_to(role: :writing, shard: :one) do
        User.first # reads from default replica
        Dog.first # reads from shard one primary
      end
    
      User.first # reads from default replica
      Dog.first # reads from default replica
    
      ApplicationRecord.connected_to(role: :writing, shard: :two) do
        User.first # reads from shard two primary
        Dog.first # reads from default replica
      end
    end
    

    Eileen M. Uchitelle, John Crepezzi

  • Allow double-dash comment syntax when querying read-only databases

    James Adam

  • Add values_at method.

    Returns an array containing the values associated with the given methods.

    topic = Topic.first
    topic.values_at(:title, :author_name)
    # => ["Budget", "Jason"]
    

    Similar to Hash#values_at but on an Active Record instance.

    Guillaume Briday

  • Fix read_attribute_before_type_cast to consider attribute aliases.

    Marcelo Lauxen

  • Support passing record to uniqueness validator :conditions callable:

    class Article < ApplicationRecord
      validates_uniqueness_of :title, conditions: ->(article) {
        published_at = article.published_at
        where(published_at: published_at.beginning_of_year..published_at.end_of_year)
      }
    end
    

    Eliot Sykes

  • BatchEnumerator#update_all and BatchEnumerator#delete_all now return the
    total number of rows affected, just like their non-batched counterparts.

    Person.in_batches.update_all("first_name = 'Eugene'") # => 42
    Person.in_batches.delete_all # => 42
    

    Fixes #40287.

    Eugene Kenny

  • Add support for PostgreSQL interval data type with conversion to
    ActiveSupport::Duration when loading records from database and
    serialization to ISO 8601 formatted duration string on save.
    Add support to define a column in migrations and get it in a schema dump.
    Optional column precision is supported.

    To use this in 6.1, you need to place the next string to your model file:

    attribute :duration, :interval
    

    To keep old behavior until 6.2 is released:

    attribute :duration, :string
    

    Example:

    create_table :events do |t|
      t.string   :name
      t.interval :duration
    end
    
    class Event < ApplicationRecord
      attribute :duration, :interval
    end
    
    Event.create!(name: 'Rock Fest', duration: 2.days)
    Event.last.duration # => 2 days
    Event.last.duration.iso8601 # => "P2D"
    Event.new(duration: 'P1DT12H3S').duration # => 1 day, 12 hours, and 3 seconds
    Event.new(duration: '1 day') # Unknown value will be ignored and NULL will be written to database
    

    Andrey Novikov

  • Allow associations supporting the dependent: key to take dependent: :destroy_async.

    class Account < ActiveRecord::Base
        belongs_to :supplier, dependent: :destroy_async
    end
    

    :destroy_async will enqueue a job to destroy associated records in the background.

    DHH, George Claghorn, Cory Gwin, Rafael Mendonça França, Adrianna Chang

  • Add SKIP_TEST_DATABASE environment variable to disable modifying the test database when rails db:create and rails db:drop are called.

    Jason Schweier

  • connects_to can only be called on ActiveRecord::Base or abstract classes.

    Ensure that connects_to can only be called from ActiveRecord::Base or abstract classes. This protects the application from opening duplicate or too many connections.

    Eileen M. Uchitelle, John Crepezzi

  • All connection adapters execute now raises ActiveRecord::ConnectionNotEstablished rather than
    ActiveRecord::StatementInvalid when they encounter a connection error.

    Jean Boussier

  • Mysql2Adapter#quote_string now raises ActiveRecord::ConnectionNotEstablished rather than
    ActiveRecord::StatementInvalid when it can't connect to the MySQL server.

    Jean Boussier

  • Add support for check constraints that are NOT VALID via validate: false (PostgreSQL-only).

    Alex Robbin

  • Ensure the default configuration is considered primary or first for an environment

    If a multiple database application provides a configuration named primary, that will be treated as default. In applications that do not have a primary entry, the default database configuration will be the first configuration for an environment.

    Eileen M. Uchitelle

  • Allow where references association names as joined table name aliases.

    class Comment < ActiveRecord::Base
      enum label: [:default, :child]
      has_many :children, class_name: "Comment", foreign_key: :parent_id
    end
    
    # ... FROM comments LEFT OUTER JOIN comments children ON ... WHERE children.label = 1
    Comment.includes(:children).where("children.label": "child")
    

    Ryuta Kamizono

  • Support storing demodulized class name for polymorphic type.

    Before Rails 6.1, storing demodulized class name is supported only for STI type
    by store_full_sti_class class attribute.

    Now store_full_class_name class attribute can handle both STI and polymorphic types.

    Ryuta Kamizono

  • Deprecate rails db:structure:{load, dump} tasks and extend
    rails db:schema:{load, dump} tasks to work with either :ruby or :sql format,
    depending on config.active_record.schema_format configuration value.

    fatkodima

  • Respect the select values for eager loading.

    post = Post.select("UPPER(title) AS title").first
    post.title # => "WELCOME TO THE WEBLOG"
    post.body  # => ActiveModel::MissingAttributeError
    
    # Rails 6.0 (ignore the `select` values)
    post = Post.select("UPPER(title) AS title").eager_load(:comments).first
    post.title # => "Welcome to the weblog"
    post.body  # => "Such a lovely day"
    
    # Rails 6.1 (respect the `select` values)
    post = Post.select("UPPER(title) AS title").eager_load(:comments).first
    post.title # => "WELCOME TO THE WEBLOG"
    post.body  # => ActiveModel::MissingAttributeError
    

    Ryuta Kamizono

  • Allow attribute's default to be configured but keeping its own type.

    class Post < ActiveRecord::Base
      attribute :written_at, default: -> { Time.now.utc }
    end
    
    # Rails 6.0
    Post.type_for_attribute(:written_at) # => #<Type::Value ... precision: nil, ...>
    
    # Rails 6.1
    Post.type_for_attribute(:written_at) # => #<Type::DateTime ... precision: 6, ...>
    

    Ryuta Kamizono

  • Allow default to be configured for Enum.

    class Book < ActiveRecord::Base
      enum status: [:proposed, :written, :published], _default: :published
    end
    
    Book.new.status # => "published"
    

    Ryuta Kamizono

  • Deprecate YAML loading from legacy format older than Rails 5.0.

    Ryuta Kamizono

  • Added the setting ActiveRecord::Base.immutable_strings_by_default, which
    allows you to specify that all string columns should be frozen unless
    otherwise specified. This will reduce memory pressure for applications which
    do not generally mutate string properties of Active Record objects.

    Sean Griffin, Ryuta Kamizono

  • Deprecate map! and collect! on ActiveRecord::Result.

    Ryuta Kamizono

  • Support relation.and for intersection as Set theory.

    david_and_mary = Author.where(id: [david, mary])
    mary_and_bob   = Author.where(id: [mary, bob])
    
    david_and_mary.merge(mary_and_bob) # => [mary, bob]
    
    david_and_mary.and(mary_and_bob) # => [mary]
    david_and_mary.or(mary_and_bob)  # => [david, mary, bob]
    

    Ryuta Kamizono

  • Merging conditions on the same column no longer maintain both conditions,
    and will be consistently replaced by the latter condition in Rails 6.2.
    To migrate to Rails 6.2's behavior, use relation.merge(other, rewhere: true).

    # Rails 6.1 (IN clause is replaced by merger side equality condition)
    Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
    
    # Rails 6.1 (both conflict conditions exists, deprecated)
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
    
    # Rails 6.1 with rewhere to migrate to Rails 6.2's behavior
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
    
    # Rails 6.2 (same behavior with IN clause, mergee side condition is consistently replaced)
    Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
    

    Ryuta Kamizono

  • Do not mark Postgresql MAC address and UUID attributes as changed when the assigned value only varies by case.

    Peter Fry

  • Resolve issue with insert_all unique_by option when used with expression index.

    When the :unique_by option of ActiveRecord::Persistence.insert_all and
    ActiveRecord::Persistence.upsert_all was used with the name of an expression index, an error
    was raised. Adding a guard around the formatting behavior for the :unique_by corrects this.

    Usage:

    create_table :books, id: :integer, force: true do |t|
      t.column :name, :string
      t.index "lower(name)", unique: true
    end
    
    Book.insert_all [{ name: "MyTest" }], unique_by: :index_books_on_lower_name
    

    Fixes #39516.

    Austen Madden

  • Add basic support for CHECK constraints to database migrations.

    Usage:

    add_check_constraint :products, "price > 0", name: "price_check"
    remove_check_constraint :products, name: "price_check"
    

    fatkodima

  • Add ActiveRecord::Base.strict_loading_by_default and ActiveRecord::Base.strict_loading_by_default=
    to enable/disable strict_loading mode by default for a model. The configuration's value is
    inheritable by subclasses, but they can override that value and it will not impact parent class.

    Usage:

    class Developer < ApplicationRecord
      self.strict_loading_by_default = true
    
      has_many :projects
    end
    
    dev = Developer.first
    dev.projects.first
    # => ActiveRecord::StrictLoadingViolationError Exception: Developer is marked as strict_loading and Project cannot be lazily loaded.
    

    bogdanvlviv

  • Deprecate passing an Active Record object to quote/type_cast directly.

    Ryuta Kamizono

  • Default engine ENGINE=InnoDB is no longer dumped to make schema more agnostic.

    Before:

    create_table "accounts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
    end
    

    After:

    create_table "accounts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
    end
    

    Ryuta Kamizono

  • Added delegated type as an alternative to single-table inheritance for representing class hierarchies.
    See ActiveRecord::DelegatedType for the full description.

    DHH

  • Deprecate aggregations with group by duplicated fields.

    To migrate to Rails 6.2's behavior, use uniq!(:group) to deduplicate group fields.

    accounts = Account.group(:firm_id)
    
    # duplicated group fields, deprecated.
    accounts.merge(accounts.where.not(credit_limit: nil)).sum(:credit_limit)
    # => {
    #   [1, 1] => 50,
    #   [2, 2] => 60
    # }
    
    # use `uniq!(:group)` to deduplicate group fields.
    accounts.merge(accounts.where.not(credit_limit: nil)).uniq!(:group).sum(:credit_limit)
    # => {
    #   1 => 50,
    #   2 => 60
    # }
    

    Ryuta Kamizono

  • Deprecate duplicated query annotations.

    To migrate to Rails 6.2's behavior, use uniq!(:annotate) to deduplicate query annotations.

    accounts = Account.where(id: [1, 2]).annotate("david and mary")
    
    # duplicated annotations, deprecated.
    accounts.merge(accounts.rewhere(id: 3))
    # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */ /* david and mary */
    
    # use `uniq!(:annotate)` to deduplicate annotations.
    accounts.merge(accounts.rewhere(id: 3)).uniq!(:annotate)
    # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */
    

    Ryuta Kamizono

  • Resolve conflict between counter cache and optimistic locking.

    Bump an Active Record instance's lock version after updating its counter
    cache. This avoids raising an unnecessary ActiveRecord::StaleObjectError
    upon subsequent transactions by maintaining parity with the corresponding
    database record's lock_version column.

    Fixes #16449.

    Aaron Lipman

  • Support merging option :rewhere to allow mergee side condition to be replaced exactly.

    david_and_mary = Author.where(id: david.id..mary.id)
    
    # both conflict conditions exists
    david_and_mary.merge(Author.where(id: bob)) # => []
    
    # mergee side condition is replaced by rewhere
    david_and_mary.merge(Author.rewhere(id: bob)) # => [bob]
    
    # mergee side condition is replaced by rewhere option
    david_and_mary.merge(Author.where(id: bob), rewhere: true) # => [bob]
    

    Ryuta Kamizono

  • Add support for finding records based on signed ids, which are tamper-proof, verified ids that can be
    set to expire and scoped with a purpose. This is particularly useful for things like password reset
    or email verification, where you want the bearer of the signed id to be able to interact with the
    underlying record, but usually only within a certain time period.

    signed_id = User.first.signed_id expires_in: 15.minutes, purpose: :password_reset
    
    User.find_signed signed_id # => nil, since the purpose does not match
    
    travel 16.minutes
    User.find_signed signed_id, purpose: :password_reset # => nil, since the signed id has expired
    
    travel_back
    User.find_signed signed_id, purpose: :password_reset # => User.first
    
    User.find_signed! "bad data" # => ActiveSupport::MessageVerifier::InvalidSignature
    

    DHH

  • Support ALGORITHM = INSTANT DDL option for index operations on MySQL.

    Ryuta Kamizono

  • Fix index creation to preserve index comment in bulk change table on MySQL.

    Ryuta Kamizono

  • Allow unscope to be aware of table name qualified values.

    It is possible to unscope only the column in the specified table.

    posts = Post.joins(:comments).group(:"posts.hidden")
    posts = posts.where("posts.hidden": false, "comments.hidden": false)
    
    posts.count
    # => { false => 10 }
    
    # unscope both hidden columns
    posts.unscope(where: :hidden).count
    # => { false => 11, true => 1 }
    
    # unscope only comments.hidden column
    posts.unscope(where: :"comments.hidden").count
    # => { false => 11 }
    

    Ryuta Kamizono, Slava Korolev

  • Fix rewhere to truly overwrite collided where clause by new where clause.

    steve = Person.find_by(name: "Steve")
    david = Author.find_by(name: "David")
    
    relation = Essay.where(writer: steve)
    
    # Before
    relation.rewhere(writer: david).to_a # => []
    
    # After
    relation.rewhere(writer: david).to_a # => [david]
    

    Ryuta Kamizono

  • Inspect time attributes with subsec and time zone offset.

    p Knot.create
    => #<Knot id: 1, created_at: "2016-05-05 01:29:47.116928000 +0000">
    

    akinomaeni, Jonathan Hefner

  • Deprecate passing a column to type_cast.

    Ryuta Kamizono

  • Deprecate in_clause_length and allowed_index_name_length in DatabaseLimits.

    Ryuta Kamizono

  • Support bulk insert/upsert on relation to preserve scope values.

    Josef Šimánek, Ryuta Kamizono

  • Preserve column comment value on changing column name on MySQL.

    Islam Taha

  • Add support for if_exists option for removing an index.

    The remove_index method can take an if_exists option. If this is set to true an error won't be raised if the index doesn't exist.

    Eileen M. Uchitelle

  • Remove ibm_db, informix, mssql, oracle, and oracle12 Arel visitors which are not used in the code base.

    Ryuta Kamizono

  • Prevent build_association from touching a parent record if the record isn't persisted for has_one associations.

    Fixes #38219.

    Josh Brody

  • Add support for if_not_exists option for adding index.

    The add_index method respects if_not_exists option. If it is set to true
    index won't be added.

    Usage:

      add_index :users, :account_id, if_not_exists: true
    

    The if_not_exists option passed to create_table also gets propagated to indexes
    created within that migration so that if table and its indexes exist then there is no
    attempt to create them again.

    Prathamesh Sonpatki

  • Add ActiveRecord::Base#previously_new_record? to show if a record was new before the last save.

    Tom Ward

  • Support descending order for find_each, find_in_batches, and in_batches.

    Batch processing methods allow you to work with the records in batches, greatly reducing memory consumption, but records are always batched from oldest id to newest.

    This change allows reversing the order, batching from newest to oldest. This is useful when you need to process newer batches of records first.

    Pass order: :desc to yield batches in descending order. The default remains order: :asc.

    Person.find_each(order: :desc) do |person|
      person.party_all_night!
    end
    

    Alexey Vasiliev

  • Fix insert_all with enum values.

    Fixes #38716.

    Joel Blum

  • Add support for db:rollback:name for multiple database applications.

    Multiple database applications will now raise if db:rollback is call and recommend using the db:rollback:[NAME] to rollback migrations.

    Eileen M. Uchitelle

  • Relation#pick now uses already loaded results instead of making another query.

    Eugene Kenny

  • Deprecate using return, break or throw to exit a transaction block after writes.

    Dylan Thacker-Smith

  • Dump the schema or structure of a database when calling db:migrate:name.

    In previous versions of Rails, rails db:migrate would dump the schema of the database. In Rails 6, that holds true (rails db:migrate dumps all databases' schemas), but rails db:migrate:name does not share that behavior.

    Going forward, calls to rails db:migrate:name will dump the schema (or structure) of the database being migrated.

    Kyle Thompson

  • Reset the ActiveRecord::Base connection after rails db:migrate:name.

    When rails db:migrate has finished, it ensures the ActiveRecord::Base connection is reset to its original configuration. Going forward, rails db:migrate:name will have the same behavior.

    Kyle Thompson

  • Disallow calling connected_to on subclasses of ActiveRecord::Base.

    Behavior has not changed here but the previous API could be misleading to people who thought it would switch connections for only that class. connected_to switches the context from which we are getting connections, not the connections themselves.

    Eileen M. Uchitelle, John Crepezzi

  • Add support for horizontal sharding to connects_to and connected_to.

    Applications can now connect to multiple shards and switch between their shards in an application. Note that the shard swapping is still a manual process as this change does not include an API for automatic shard swapping.

    Usage:

    Given the following configuration:

    # config/database.yml
    production:
      primary:
        database: my_database
      primary_shard_one:
        database: my_database_shard_one
    

    Connect to multiple shards:

    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    
      connects_to shards: {
        default: { writing: :primary },
        shard_one: { writing: :primary_shard_one }
      }
    

    Swap between shards in your controller / model code:

    ActiveRecord::Base.connected_to(shard: :shard_one) do
      # Read from shard one
    end
    

    The horizontal sharding API also supports read replicas. See guides for more details.

    Eileen M. Uchitelle, John Crepezzi

  • Deprecate spec_name in favor of name on database configurations.

    The accessors for spec_name on configs_for and DatabaseConfig are deprecated. Please use name instead.

    Deprecated behavior:

    db_config = ActiveRecord::Base.configs_for(env_name: "development", spec_name: "primary")
    db_config.spec_name
    

    New behavior:

    db_config = ActiveRecord::Base.configs_for(env_name: "development", name: "primary")
    db_config.name
    

    Eileen M. Uchitelle

  • Add additional database-specific rake tasks for multi-database users.

    Previously, rails db:create, rails db:drop, and rails db:migrate were the only rails tasks that could operate on a single
    database. For example:

    rails db:create
    rails db:create:primary
    rails db:create:animals
    rails db:drop
    rails db:drop:primary
    rails db:drop:animals
    rails db:migrate
    rails db:migrate:primary
    rails db:migrate:animals
    

    With these changes, rails db:schema:dump, rails db:schema:load, rails db:structure:dump, rails db:structure:load and
    rails db:test:prepare can additionally operate on a single database. For example:

    rails db:schema:dump
    rails db:schema:dump:primary
    rails db:schema:dump:animals
    rails db:schema:load
    rails db:schema:load:primary
    rails db:schema:load:animals
    rails db:structure:dump
    rails db:structure:dump:primary
    rails db:structure:dump:animals
    rails db:structure:load
    rails db:structure:load:primary
    rails db:structure:load:animals
    rails db:test:prepare
    rails db:test:prepare:primary
    rails db:test:prepare:animals
    

    Kyle Thompson

  • Add support for strict_loading mode on association declarations.

    Raise an error if attempting to load a record from an association that has been marked as strict_loading unless it was explicitly eager loaded.

    Usage:

    class Developer < ApplicationRecord
      has_many :projects, strict_loading: true
    end
    
    dev = Developer.first
    dev.projects.first
    # => ActiveRecord::StrictLoadingViolationError: The projects association is marked as strict_loading and cannot be lazily loaded.
    

    Kevin Deisz

  • Add support for strict_loading mode to prevent lazy loading of records.

    Raise an error if a parent record is marked as strict_loading and attempts to lazily load its associations. This is useful for finding places you may want to preload an association and avoid additional queries.

    Usage:

    dev = Developer.strict_loading.first
    dev.audit_logs.to_a
    # => ActiveRecord::StrictLoadingViolationError: Developer is marked as strict_loading and AuditLog cannot be lazily loaded.
    

    Eileen M. Uchitelle, Aaron Patterson

  • Add support for PostgreSQL 11+ partitioned indexes when using upsert_all.

    Sebastián Palma

  • Adds support for if_not_exists to add_column and if_exists to remove_column.

    Applications can set their migrations to ignore exceptions raised when adding a column that already exists or when removing a column that does not exist.

    Example Usage:

    class AddColumnTitle < ActiveRecord::Migration[6.1]
      def change
        add_column :posts, :title, :string, if_not_exists: true
      end
    end
    
    class RemoveColumnTitle < ActiveRecord::Migration[6.1]
      def change
        remove_column :posts, :title, if_exists: true
      end
    end
    

    Eileen M. Uchitelle

  • Regexp-escape table name for MS SQL Server.

    Add Regexp.escape to one method in ActiveRecord, so that table names with regular expression characters in them work as expected. Since MS SQL Server uses "[" and "]" to quote table and column names, and those characters are regular expression characters, methods like pluck and select fail in certain cases when used with the MS SQL Server adapter.

    Larry Reid

  • Store advisory locks on their own named connection.

    Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped.

    In order to fix this we are storing the advisory lock on a new connection with the connection specification name AdvisoryLockBase. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this.

    Eileen M. Uchitelle, John Crepezzi

  • Allow schema cache path to be defined in the database configuration file.

    For example:

    development:
      adapter: postgresql
      database: blog_development
      pool: 5
      schema_cache_path: tmp/schema/main.yml
    

    Katrina Owen

  • Deprecate #remove_connection in favor of #remove_connection_pool when called on the handler.

    #remove_connection is deprecated in order to support returning a DatabaseConfig object instead of a Hash. Use #remove_connection_pool, #remove_connection will be removed in 6.2.

    Eileen M. Uchitelle, John Crepezzi

  • Deprecate #default_hash and it's alias #[] on database configurations.

    Applications should use configs_for. #default_hash and #[] will be removed in 6.2.

    Eileen M. Uchitelle, John Crepezzi

  • Add scale support to ActiveRecord::Validations::NumericalityValidator.

    Gannon McGibbon

  • Find orphans by looking for missing relations through chaining where.missing:

    Before:

    Post.left_joins(:author).where(authors: { id: nil })
    

    After:

    Post.where.missing(:author)
    

    Tom Rossi

  • Ensure :reading connections always raise if a write is attempted.

    Now Rails will raise an ActiveRecord::ReadOnlyError if any connection on the reading handler attempts to make a write. If your reading role needs to write you should name the role something other than :reading.

    Eileen M. Uchitelle

  • Deprecate "primary" as the connection_specification_name for ActiveRecord::Base.

    "primary" has been deprecated as the connection_specification_name for ActiveRecord::Base in favor of using "ActiveRecord::Base". This change affects calls to ActiveRecord::Base.connection_handler.retrieve_connection and ActiveRecord::Base.connection_handler.remove_connection. If you're calling these methods with "primary", please switch to "ActiveRecord::Base".

    Eileen M. Uchitelle, John Crepezzi

  • Add ActiveRecord::Validations::NumericalityValidator with
    support for casting floats using a database columns' precision value.

    Gannon McGibbon

  • Enforce fresh ETag header after a collection's contents change by adding
    ActiveRecord::Relation#cache_key_with_version. This method will be used by
    ActionController::ConditionalGet to ensure that when collection cache versioning
    is enabled, requests using ConditionalGet don't return the same ETag header
    after a collection is modified.

    Fixes #38078.

    Aaron Lipman

  • Skip test database when running db:create or db:drop in development
    with DATABASE_URL set.

    Brian Buchalter

  • Don't allow mutations on the database configurations hash.

    Freeze the configurations hash to disallow directly changing it. If applications need to change the hash, for example to create databases for parallelization, they should use the DatabaseConfig object directly.

    Before:

    @db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary")
    @db_config.configuration_hash.merge!(idle_timeout: "0.02")
    

    After:

    @db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary")
    config = @db_config.configuration_hash.merge(idle_timeout: "0.02")
    db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(@db_config.env_name, @db_config.spec_name, config)
    

    Eileen M. Uchitelle, John Crepezzi

  • Remove :connection_id from the sql.active_record notification.

    Aaron Patterson, Rafael Mendonça França

  • The :name key will no longer be returned as part of DatabaseConfig#configuration_hash. Please use DatabaseConfig#owner_name instead.

    Eileen M. Uchitelle, John Crepezzi

  • ActiveRecord's belongs_to_required_by_default flag can now be set per model.

    You can now opt-out/opt-in specific models from having their associations required
    by default.

    This change is meant to ease the process of migrating all your models to have
    their association required.

    Edouard Chin

  • The connection_config method has been deprecated, please use connection_db_config instead which will return a DatabaseConfigurations::DatabaseConfig instead of a Hash.

    Eileen M. Uchitelle, John Crepezzi

  • Retain explicit selections on the base model after applying includes and joins.

    Resolves #34889.

    Patrick Rebsch

  • The database kwarg is deprecated without replacement because it can't be used for sharding and creates an issue if it's used during a request. Applications that need to create new connections should use connects_to instead.

    Eileen M. Uchitelle, John Crepezzi

  • Allow attributes to be fetched from Arel node groupings.

    Jeff Emminger, Gannon McGibbon

  • A database URL can now contain a querystring value that contains an equal sign. This is needed to support passing PostgreSQL options.

    Joshua Flanagan

  • Calling methods like establish_connection with a Hash which is invalid (eg: no adapter) will now raise an error the same way as connections defined in config/database.yml.

    John Crepezzi

  • Specifying implicit_order_column now subsorts the records by primary key if available to ensure deterministic results.

    Paweł Urbanek

  • where(attr => []) now loads an empty result without making a query.

    John Hawthorn

  • Fixed the performance regression for primary_keys introduced MySQL 8.0.

    Hiroyuki Ishii

  • Add support for belongs_to to has_many inversing.

    Gannon McGibbon

  • Allow length configuration for has_secure_token method. The minimum length
    is set at 24 characters.

    Before:

    has_secure_token :auth_token
    

    After:

    has_secure_token :default_token             # 24 characters
    has_secure_token :auth_token, length: 36    # 36 characters
    has_secure_token :invalid_token, length: 12 # => ActiveRecord::SecureToken::MinimumLengthError
    

    Bernardo de Araujo

  • Deprecate DatabaseConfigurations#to_h. These connection hashes are still available via ActiveRecord::Base.configurations.configs_for.

    Eileen Uchitelle, John Crepezzi

  • Add DatabaseConfig#configuration_hash to return database configuration hashes with symbol keys, and use all symbol-key configuration hashes internally. Deprecate DatabaseConfig#config which returns a String-keyed Hash with the same values.

    John Crepezzi, Eileen Uchitelle

  • Allow column names to be passed to remove_index positionally along with other options.

    Passing other options can be necessary to make remove_index correctly reversible.

    Before:

    add_index    :reports, :report_id               # => works
    add_index    :reports, :report_id, unique: true # => works
    remove_index :reports, :report_id               # => works
    remove_index :reports, :report_id, unique: true # => ArgumentError
    

    After:

    remove_index :reports, :report_id, unique: true # => works
    

    Eugene Kenny

  • Allow bulk ALTER statements to drop and recreate indexes with the same name.

    Eugene Kenny

  • insert, insert_all, upsert, and upsert_all now clear the query cache.

    Eugene Kenny

  • Call while_preventing_writes directly from connected_to.

    In some cases application authors want to use the database switching middleware and make explicit calls with connected_to. It's possible for an app to turn off writes and not turn them back on by the time we call connected_to(role: :writing).

    This change allows apps to fix this by assuming if a role is writing we want to allow writes, except in the case it's explicitly turned off.

    Eileen M. Uchitelle

  • Improve detection of ActiveRecord::StatementTimeout with mysql2 adapter in the edge case when the query is terminated during filesort.

    Kir Shatrov

  • Stop trying to read yaml file fixtures when loading Active Record fixtures.

    Gannon McGibbon

  • Deprecate .reorder(nil) with .first / .first! taking non-deterministic result.

    To continue taking non-deterministic result, use .take / .take! instead.

    Ryuta Kamizono

  • Preserve user supplied joins order as much as possible.

    Fixes #36761, #34328, #24281, #12953.

    Ryuta Kamizono

  • Allow matches_regex and does_not_match_regexp on the MySQL Arel visitor.

    James Pearson

  • Allow specifying fixtures to be ignored by setting ignore in YAML file's '_fixture' section.

    Tongfei Gao

  • Make the DATABASE_URL env variable only affect the primary connection. Add new env variables for multiple databases.

    John Crepezzi, Eileen Uchitelle

  • Add a warning for enum elements with 'not_' prefix.

    class Foo
      enum status: [:sent, :not_sent]
    end
    

    Edu Depetris

  • Make currency symbols optional for money column type in PostgreSQL.

    Joel Schneider

  • Add support for beginless ranges, introduced in Ruby 2.7.

    Josh Goodall

  • Add database_exists? method to connection adapters to check if a database exists.

    Guilherme Mansur

  • Loading the schema for a model that has no table_name raises a TableNotSpecified error.

    Guilherme Mansur, Eugene Kenny

  • PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.

    Fixes #36022.

    Ryuta Kamizono

  • Make ActiveRecord ConnectionPool.connections method thread-safe.

    Fixes #36465.

    Jeff Doering

  • Add support for multiple databases to rails db:abort_if_pending_migrations.

    Mark Lee

  • Fix sqlite3 collation parsing when using decimal columns.

    Martin R. Schuster

  • Fix invalid schema when primary key column has a comment.

    Fixes #29966.

    Guilherme Goettems Schneider

  • Fix table comment also being applied to the primary key column.

    Guilherme Goettems Schneider

  • Allow generated create_table migrations to include or skip timestamps.

    Michael Duchemin

Action View

  • SanitizeHelper.sanitized_allowed_attributes and SanitizeHelper.sanitized_allowed_tags
    call safe_list_sanitizer's class method

    Fixes #39586

    Taufiq Muhammadi

  • Change form_with to generate non-remote forms by default.

    form_with would generate a remote form by default. This would confuse
    users because they were forced to handle remote requests.

    All new 6.1 applications will generate non-remote forms by default.
    When upgrading a 6.0 application you can enable remote forms by default by
    setting config.action_view.form_with_generates_remote_forms to true.

    Petrik de Heus

  • Yield translated strings to calls of ActionView::FormBuilder#button
    when a block is given.

    Sean Doyle

  • Alias ActionView::Helpers::Tags::Label::LabelBuilder#translation to
    #to_s so that form.label calls can yield that value to their blocks.

    Sean Doyle

  • Rename the new TagHelper#class_names method to TagHelper#token_list,
    and make the original available as an alias.

    token_list("foo", "foo bar")
    # => "foo bar"
    

    Sean Doyle

  • ARIA Array and Hash attributes are treated as space separated DOMTokenList
    values. This is useful when declaring lists of label text identifiers in
    aria-labelledby or aria-describedby.

    tag.input type: 'checkbox', name: 'published', aria: {
      invalid: @post.errors[:published].any?,
      labelledby: ['published_context', 'published_label'],
      describedby: { published_errors: @post.errors[:published].any? }
    }
    #=> <input
          type="checkbox" name="published" aria-invalid="true"
          aria-labelledby="published_context published_label"
          aria-describedby="published_errors"
        >
    

    Sean Doyle

  • Remove deprecated escape_whitelist from ActionView::Template::Handlers::ERB.

    Rafael Mendonça França

  • Remove deprecated find_all_anywhere from ActionView::Resolver.

    Rafael Mendonça França

  • Remove deprecated formats from ActionView::Template::HTML.

    Rafael Mendonça França

  • Remove deprecated formats from ActionView::Template::RawFile.

    Rafael Mendonça França

  • Remove deprecated formats from ActionView::Template::Text.

    Rafael Mendonça França

  • Remove deprecated find_file from ActionView::PathSet.

    Rafael Mendonça França

  • Remove deprecated rendered_format from ActionView::LookupContext.

    Rafael Mendonça França

  • Remove deprecated find_file from ActionView::ViewPaths.

    Rafael Mendonça França

  • Require that ActionView::Base subclasses implement #compiled_method_container.

    Rafael Mendonça França

  • Remove deprecated support to pass an object that is not a ActionView::LookupContext as the first argument
    in ActionView::Base#initialize.

    Rafael Mendonça França

  • Remove deprecated format argument ActionView::Base#initialize.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#refresh.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#original_encoding.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#variants.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#formats.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#virtual_path=.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#updated_at.

    Rafael Mendonça França

  • Remove deprecated updated_at argument required on ActionView::Template#initialize.

    Rafael Mendonça França

  • Make locals argument required on ActionView::Template#initialize.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template.finalize_compiled_template_methods.

    Rafael Mendonça França

  • Remove deprecated config.action_view.finalize_compiled_template_methods

    Rafael Mendonça França

  • Remove deprecated support to calling ActionView::ViewPaths#with_fallback with a block.

    Rafael Mendonça França

  • Remove deprecated support to passing absolute paths to render template:.

    Rafael Mendonça França

  • Remove deprecated support to passing relative paths to render file:.

    Rafael Mendonça França

  • Remove support to template handlers that don't accept two arguments.

    Rafael Mendonça França

  • Remove deprecated pattern argument in ActionView::Template::PathResolver.

    Rafael Mendonça França

  • Remove deprecated support to call private methods from object in some view helpers.

    Rafael Mendonça França

  • ActionView::Helpers::TranslationHelper#translate accepts a block, yielding
    the translated text and the fully resolved translation key:

    <%= translate(".relative_key") do |translation, resolved_key| %>
      <span title="<%= resolved_key %>"><%= translation %></span>
    <% end %>
    

    Sean Doyle

  • Ensure cache fragment digests include all relevant template dependencies when
    fragments are contained in a block passed to the render helper. Remove the
    virtual_path keyword arguments found in CacheHelper as they no longer possess
    any function following 1581cab.

    Fixes #38984.

    Aaron Lipman

  • Deprecate config.action_view.raise_on_missing_translations in favor of
    config.i18n.raise_on_missing_translations.

    New generalized configuration option now determines whether an error should be raised
    for missing translations in controllers and views.

    fatkodima

  • Instrument layout rendering in TemplateRenderer#render_with_layout as render_layout.action_view,
    and include (when necessary) the layout's virtual path in notification payloads for collection and partial renders.

    Zach Kemp

  • ActionView::Base.annotate_rendered_view_with_filenames annotates HTML output with template file names.

    Joel Hawksley, Aaron Patterson

  • ActionView::Helpers::TranslationHelper#translate returns nil when
    passed default: nil without a translation matching I18n#translate.

    Stefan Wrobel

  • OptimizedFileSystemResolver prefers template details in order of locale,
    formats, variants, handlers.

    Iago Pimenta

  • Added class_names helper to create a CSS class value with conditional classes.

    Joel Hawksley, Aaron Patterson

  • Add support for conditional values to TagBuilder.

    Joel Hawksley

  • ActionView::Helpers::FormOptionsHelper#select should mark option for nil as selected.

    @post = Post.new
    @post.category = nil
    
    # Before
    select("post", "category", none: nil, programming: 1, economics: 2)
    # =>
    # <select name="post[category]" id="post_category">
    #   <option value="">none</option>
    #  <option value="1">programming</option>
    #  <option value="2">economics</option>
    # </select>
    
    # After
    select("post", "category", none: nil, programming: 1, economics: 2)
    # =>
    # <select name="post[category]" id="post_category">
    #   <option selected="selected" value="">none</option>
    #  <option value="1">programming</option>
    #  <option value="2">economics</option>
    # </select>
    

    bogdanvlviv

  • Log lines for partial renders and started template renders are now
    emitted at the DEBUG level instead of INFO.

    Completed template renders are still logged at the INFO level.

    DHH

  • ActionView::Helpers::SanitizeHelper: support rails-html-sanitizer 1.1.0.

    Juanito Fatas

  • Added phone_to helper method to create a link from mobile numbers.

    Pietro Moro

  • annotated_source_code returns an empty array so TemplateErrors without a
    template in the backtrace are surfaced properly by DebugExceptions.

    Guilherme Mansur, Kasper Timm Hansen

  • Add autoload for SyntaxErrorInTemplate so syntax errors are correctly raised by DebugExceptions.

    Guilherme Mansur, Gannon McGibbon

  • RenderingHelper supports rendering objects that respond_to? :render_in.

    Joel Hawksley, Natasha Umer, Aaron Patterson, Shawn Allen, Emily Plummer, Diana Mounter, John Hawthorn, Nathan Herald, Zaid Zawaideh, Zach Ahn

  • Fix select_tag so that it doesn't change options when include_blank is present.

    Younes SERRAJ

Action Pack

  • Support for the HTTP header Feature-Policy has been revised to reflect
    its rename to Permissions-Policy.

    Rails.application.config.permissions_policy do |p|
      p.camera     :none
      p.gyroscope  :none
      p.microphone :none
      p.usb        :none
      p.fullscreen :self
      p.payment    :self, "https://secure-example.com"
    end
    

    Julien Grillot

  • Allow ActionDispatch::HostAuthorization to exclude specific requests.

    Host Authorization checks can be skipped for specific requests. This allows for health check requests to be permitted for requests with missing or non-matching host headers.

    Chris Bisnett

  • Add config.action_dispatch.request_id_header to allow changing the name of
    the unique X-Request-Id header

    Arlston Fernandes

  • Deprecate config.action_dispatch.return_only_media_type_on_content_type.

    Rafael Mendonça França

  • Change ActionDispatch::Response#content_type to return the full Content-Type header.

    Rafael Mendonça França

  • Remove deprecated ActionDispatch::Http::ParameterFilter.

    Rafael Mendonça França

  • Added support for exclusive no-store Cache-Control header.

    If no-store is set on Cache-Control header it is exclusive (all other cache directives are dropped).

    Chris Kruger

  • Catch invalid UTF-8 parameters for POST requests and respond with BadRequest.

    Additionally, perform #set_binary_encoding in ActionDispatch::Http::Request#GET and
    ActionDispatch::Http::Request#POST prior to validating encoding.

    Adrianna Chang

  • Allow assert_recognizes routing assertions to work on mounted root routes.

    Gannon McGibbon

  • Change default redirection status code for non-GET/HEAD requests to 308 Permanent Redirect for ActionDispatch::SSL.

    Alan Tan, Oz Ben-David

  • Fix follow_redirect! to follow redirection with same HTTP verb when following
    a 308 redirection.

    Alan Tan

  • When multiple domains are specified for a cookie, a domain will now be
    chosen only if it is equal to or is a superdomain of the request host.

    Jonathan Hefner

  • ActionDispatch::Static handles precompiled Brotli (.br) files.

    Adds to existing support for precompiled gzip (.gz) files.
    Brotli files are preferred due to much better compression.

    When the browser requests /some.js with Accept-Encoding: br,
    we check for public/some.js.br and serve that file, if present, with
    Content-Encoding: br and Vary: Accept-Encoding headers.

    Ryan Edward Hall, Jeremy Daer

  • Add raise_on_missing_translations support for controllers.

    This configuration determines whether an error should be raised for missing translations.
    It can be enabled through config.i18n.raise_on_missing_translations. Note that described
    configuration also affects raising error for missing translations in views.

    fatkodima

  • Added compact and compact! to ActionController::Parameters.

    Eugene Kenny

  • Calling each_pair or each_value on an ActionController::Parameters
    without passing a block now returns an enumerator.

    Eugene Kenny

  • fixture_file_upload now uses path relative to file_fixture_path

    Previously the path had to be relative to fixture_path.
    You can change your existing code as follow:

    # Before
    fixture_file_upload('files/dog.png')
    
    # After
    fixture_file_upload('dog.png')
    

    Edouard Chin

  • Remove deprecated force_ssl at the controller level.

    Rafael Mendonça França

  • The +helper+ class method for controllers loads helper modules specified as
    strings/symbols with String#constantize instead of require_dependency.

    Remember that support for strings/symbols is only a convenient API. You can
    always pass a module object:

    helper UtilsHelper
    

    which is recommended because it is simple and direct. When a string/symbol
    is received, helper just manipulates and inflects the argument to obtain
    that same module object.

    Xavier Noria, Jean Boussier

  • Correctly identify the entire localhost IPv4 range as trusted proxy.

    Nick Soracco

  • url_for will now use "https://" as the default protocol when
    Rails.application.config.force_ssl is set to true.

    Jonathan Hefner

  • Accept and default to base64_urlsafe CSRF tokens.

    Base64 strict-encoded CSRF tokens are not inherently websafe, which makes
    them difficult to deal with. For example, the common practice of sending
    the CSRF token to a browser in a client-readable cookie does not work properly
    out of the box: the value has to be url-encoded and decoded to survive transport.

    Now, we generate Base64 urlsafe-encoded CSRF tokens, which are inherently safe
    to transport. Validation accepts both urlsafe tokens, and strict-encoded tokens
    for backwards compatibility.

    Scott Blum

  • Support rolling deploys for cookie serialization/encryption changes.

    In a distributed configuration like rolling update, users may observe
    both old and new instances during deployment. Users may be served by a
    new instance and then by an old instance.

    That means when the server changes cookies_serializer from :marshal
    to :hybrid or the server changes use_authenticated_cookie_encryption
    from false to true, users may lose their sessions if they access the
    server during deployment.

    We added fallbacks to downgrade the cookie format when necessary during
    deployment, ensuring compatibility on both old and new instances.

    Masaki Hara

  • ActionDispatch::Request.remote_ip has ip address even when all sites are trusted.

    Before, if all X-Forwarded-For sites were trusted, the remote_ip would default to 127.0.0.1.
    Now, the furthest proxy site is used. e.g.: It now gives an ip address when using curl from the load balancer.

    Keenan Brock

  • Fix possible information leak / session hijacking vulnerability.

    The ActionDispatch::Session::MemcacheStore is still vulnerable given it requires the
    gem dalli to be updated as well.

    CVE-2019-16782.

  • Include child session assertion count in ActionDispatch::IntegrationTest.

    IntegrationTest#open_session uses dup to create the new session, which
    meant it had its own copy of @assertions. This prevented the assertions
    from being correctly counted and reported.

    Child sessions now have their attr_accessor overridden to delegate to the
    root session.

    Fixes #32142.

    Sam Bostock

  • Add SameSite protection to every written cookie.

    Enabling SameSite cookie protection is an addition to CSRF protection,
    where cookies won't be sent by browsers in cross-site POST requests when set to :lax.

    :strict disables cookies being sent in cross-site GET or POST requests.

    Passing :none disables this protection and is the same as previous versions albeit a ; SameSite=None is appended to the cookie.

    See upgrade instructions in config/initializers/new_framework_defaults_6_1.rb.

    More info here

    NB: Technically already possible as Rack supports SameSite protection, this is to ensure it's applied to all cookies

    Cédric Fabianski

  • Bring back the feature that allows loading external route files from the router.

    This feature existed back in 2012 but got reverted with the incentive that
    https://github.com/rails/routing_concerns was a better approach. Turned out
    that this wasn't fully the case and loading external route files from the router
    can be helpful for applications with a really large set of routes.
    Without this feature, application needs to implement routes reloading
    themselves and it's not straightforward.

    # config/routes.rb
    
    Rails.application.routes.draw do
      draw(:admin)
    end
    
    # config/routes/admin.rb
    
    get :foo, to: 'foo#bar'
    

    Yehuda Katz, Edouard Chin

  • Fix system test driver option initialization for non-headless browsers.

    glaszig

  • redirect_to.action_controller notifications now include the ActionDispatch::Request in
    their payloads as :request.

    Austin Story

  • respond_to#any no longer returns a response's Content-Type based on the
    request format but based on the block given.

    Example:

      def my_action
        respond_to do |format|
          format.any { render(json: { foo: 'bar' }) }
        end
      end
    
      get('my_action.csv')
    

    The previous behaviour was to respond with a text/csv Content-Type which
    is inaccurate since a JSON response is being rendered.

    Now it correctly returns a application/json Content-Type.

    Edouard Chin

  • Replaces (back)slashes in failure screenshot image paths with dashes.

    If a failed test case contained a slash or a backslash, a screenshot would be created in a
    nested directory, causing issues with tmp:clear.

    Damir Zekic

  • Add params.member? to mimic Hash behavior.

    Younes Serraj

  • process_action.action_controller notifications now include the following in their payloads:

    • :request - the ActionDispatch::Request
    • :response - the ActionDispatch::Response

    George Claghorn

  • Updated ActionDispatch::Request.remote_ip setter to clear set the instance
    remote_ip to nil before setting the header that the value is derived
    from.

    Fixes #37383.

    Norm Provost

  • ActionController::Base.log_at allows setting a different log level per request.

    # Use the debug level if a particular cookie is set.
    class ApplicationController < ActionController::Base
      log_at :debug, if: -> { cookies[:debug] }
    end
    

    George Claghorn

  • Allow system test screen shots to be taken more than once in
    a test by prefixing the file name with an incrementing counter.

    Add an environment variable RAILS_SYSTEM_TESTING_SCREENSHOT_HTML to
    enable saving of HTML during a screenshot in addition to the image.
    This uses the same image name, with the extension replaced with .html

    Tom Fakes

  • Add Vary: Accept header when using Accept header for response.

    For some requests like /users/1, Rails uses requests' Accept
    header to determine what to return. And if we don't add Vary
    in the response header, browsers might accidentally cache different
    types of content, which would cause issues: e.g. javascript got displayed
    instead of html content. This PR fixes these issues by adding Vary: Accept
    in these types of requests. For more detailed problem description, please read:

    https://github.com/rails/rails/pull/36213

    Fixes #25842.

    Stan Lo

  • Fix IntegrationTest follow_redirect! to follow redirection using the same HTTP verb when following
    a 307 redirection.

    Edouard Chin

  • System tests require Capybara 3.26 or newer.

    George Claghorn

  • Reduced log noise handling ActionController::RoutingErrors.

    Alberto Fernández-Capel

  • Add DSL for configuring HTTP Feature Policy.

    This new DSL provides a way to configure an HTTP Feature Policy at a
    global or per-controller level. Full details of HTTP Feature Policy
    specification and guidelines can be found at MDN:

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy

    Example global policy:

    Rails.application.config.feature_policy do |f|
      f.camera      :none
      f.gyroscope   :none
      f.microphone  :none
      f.usb         :none
      f.fullscreen  :self
      f.payment     :self, "https://secure.example.com"
    end
    

    Example controller level policy:

    class PagesController < ApplicationController
      feature_policy do |p|
        p.geolocation "https://example.com"
      end
    end
    

    Jacob Bednarz

  • Add the ability to set the CSP nonce only to the specified directives.

    Fixes #35137.

    Yuji Yaginuma

  • Keep part when scope option has value.

    When a route was defined within an optional scope, if that route didn't
    take parameters the scope was lost when using path helpers. This commit
    ensures scope is kept both when the route takes parameters or when it
    doesn't.

    Fixes #33219.

    Alberto Almagro

  • Added deep_transform_keys and deep_transform_keys! methods to ActionController::Parameters.

    Gustavo Gutierrez

  • Calling ActionController::Parameters#transform_keys/! without a block now returns
    an enumerator for the parameters instead of the underlying hash.

    Eugene Kenny

  • Fix strong parameters blocks all attributes even when only some keys are invalid (non-numerical).
    It should only block invalid key's values instead.

    Stan Lo

Active Job

  • Recover nano precision when serializing Time, TimeWithZone and DateTime objects.

    Alan Tan

  • Deprecate config.active_job.return_false_on_aborted_enqueue.

    Rafael Mendonça França

  • Return false when enqueuing a job is aborted.

    Rafael Mendonça França

  • While using perform_enqueued_jobs test helper enqueued jobs must be stored for the later check with
    assert_enqueued_with.

    Dmitry Polushkin

  • ActiveJob::TestCase#perform_enqueued_jobs without a block removes performed jobs from the queue.

    That way the helper can be called multiple times and not perform a job invocation multiple times.

    def test_jobs
      HelloJob.perform_later("rafael")
      perform_enqueued_jobs # only runs with "rafael"
      HelloJob.perform_later("david")
      perform_enqueued_jobs # only runs with "david"
    end
    

    Étienne Barrié

  • ActiveJob::TestCase#perform_enqueued_jobs will no longer perform retries:

    When calling perform_enqueued_jobs without a block, the adapter will
    now perform jobs that are already in the queue. Jobs that will end up in
    the queue afterwards won't be performed.

    This change only affects perform_enqueued_jobs when no block is given.

    Edouard Chin

  • Add queue name support to Que adapter.

    Brad Nauta, Wojciech Wnętrzak

  • Don't run after_enqueue and after_perform callbacks if the callback chain is halted.

    class MyJob < ApplicationJob
      before_enqueue { throw(:abort) }
      after_enqueue { # won't enter here anymore }
    end
    

    after_enqueue and after_perform callbacks will no longer run if the callback chain is halted.
    This behaviour is a breaking change and won't take effect until Rails 6.2.
    To enable this behaviour in your app right now, you can add in your app's configuration file
    config.active_job.skip_after_callbacks_if_terminated = true.

    Edouard Chin

  • Fix enqueuing and performing incorrect logging message.

    Jobs will no longer always log "Enqueued MyJob" or "Performed MyJob" when they actually didn't get enqueued/performed.

      class MyJob < ApplicationJob
        before_enqueue { throw(:abort) }
      end
    
      MyJob.perform_later # Will no longer log "Enqueued MyJob" since job wasn't even enqueued through adapter.
    

    A new message will be logged in case a job couldn't be enqueued, either because the callback chain was halted or
    because an exception happened during enqueuing. (i.e. Redis is down when you try to enqueue your job)

    Edouard Chin

  • Add an option to disable logging of the job arguments when enqueuing and executing the job.

    class SensitiveJob < ApplicationJob
      self.log_arguments = false
    
      def perform(my_sensitive_argument)
      end
    end
    

    When dealing with sensitive arguments as password and tokens it is now possible to configure the job
    to not put the sensitive argument in the logs.

    Rafael Mendonça França

  • Changes in queue_name_prefix of a job no longer affects all other jobs.

    Fixes #37084.

    Lucas Mansur

  • Allow Class and Module instances to be serialized.

    Kevin Deisz

  • Log potential matches in assert_enqueued_with and assert_performed_with.

    Gareth du Plooy

  • Add at argument to the perform_enqueued_jobs test helper.

    John Crepezzi, Eileen Uchitelle

  • assert_enqueued_with and assert_performed_with can now test jobs with relative delay.

    Vlado Cingel

  • Add jitter to ActiveJob::Exceptions.retry_on.

    ActiveJob::Exceptions.retry_on now uses a random amount of jitter in order to
    prevent the thundering herd effect. Defaults to
    15% (represented as 0.15) but overridable via the :jitter option when using retry_on.
    Jitter is applied when an Integer, ActiveSupport::Duration or :exponentially_longer, is passed to the wait argument in retry_on.

    retry_on(MyError, wait: :exponentially_longer, jitter: 0.30)
    

    Anthony Ross

Action Mailer

  • Change default queue name of the deliver (:mailers) job to be the job adapter's
    default (:default).

    Rafael Mendonça França

  • Remove deprecated ActionMailer::Base.receive in favor of Action Mailbox.

    Rafael Mendonça França

  • Fix ActionMailer assertions don't work for parameterized mail with legacy delivery job.

    bogdanvlviv

  • Added email_address_with_name to properly escape addresses with names.

    Sunny Ripert

Action Cable

  • ActionCable::Connection::Base now allows intercepting unhandled exceptions
    with rescue_from before they are logged, which is useful for error reporting
    tools and other integrations.

    Justin Talbott

  • Add ActionCable::Channel#stream_or_reject_for to stream if record is present, otherwise reject the connection

    Atul Bhosale

  • Add ActionCable::Channel#stop_stream_from and #stop_stream_for to unsubscribe from a specific stream.

    Zhang Kang

  • Add PostgreSQL subscription connection identificator.

    Now you can distinguish Action Cable PostgreSQL subscription connections among others.
    Also, you can set custom id in cable.yml configuration.

    SELECT application_name FROM pg_stat_activity;
    /*
        application_name
    ------------------------
    psql
    ActionCable-PID-42
    (2 rows)
    */
    

    Sergey Ponomarev

  • Subscription confirmations and rejections are now logged at the DEBUG level instead of INFO.

    DHH

Active Storage

  • Change default queue name of the analysis (:active_storage_analysis) and
    purge (:active_storage_purge) jobs to be the job adapter's default (:default).

    Rafael Mendonça França

  • Implement strict_loading on ActiveStorage associations.

    David Angulo

  • Remove deprecated support to pass :combine_options operations to ActiveStorage::Transformers::ImageProcessing.

    Rafael Mendonça França

  • Remove deprecated ActiveStorage::Transformers::MiniMagickTransformer.

    Rafael Mendonça França

  • Remove deprecated config.active_storage.queue.

    Rafael Mendonça França

  • Remove deprecated ActiveStorage::Downloading.

    Rafael Mendonça França

  • Add per-environment configuration support

    Pietro Moro

  • The Poppler PDF previewer renders a preview image using the original
    document's crop box rather than its media box, hiding print margins. This
    matches the behavior of the MuPDF previewer.

    Vincent Robert

  • Touch parent model when an attachment is purged.

    Víctor Pérez Rodríguez

  • Files can now be served by proxying them from the underlying storage service
    instead of redirecting to a signed service URL. Use the
    rails_storage_proxy_path and _url helpers to proxy an attached file:

    <%= image_tag rails_storage_proxy_path(@user.avatar) %>
    

    To proxy by default, set config.active_storage.resolve_model_to_route:

    # Proxy attached files instead.
    config.active_storage.resolve_model_to_route = :rails_storage_proxy
    
    <%= image_tag @user.avatar %>
    

    To redirect to a signed service URL when the default file serving strategy
    is set to proxying, use the rails_storage_redirect_path and _url helpers:

    <%= image_tag rails_storage_redirect_path(@user.avatar) %>
    

    Jonathan Fleckenstein

  • Add config.active_storage.web_image_content_types to allow applications
    to add content types (like image/webp) in which variants can be processed,
    instead of letting those images be converted to the fallback PNG format.

    Jeroen van Haperen

  • Add support for creating variants of WebP images out of the box.

    Dino Maric

  • Only enqueue analysis jobs for blobs with non-null analyzer classes.

    Gannon McGibbon

  • Previews are created on the same service as the original blob.

    Peter Zhu

  • Remove unused disposition and content_type query parameters for DiskService.

    Peter Zhu

  • Use DiskController for both public and private files.

    DiskController is able to handle multiple services by adding a
    service_name field in the generated URL in DiskService.

    Peter Zhu

  • Variants are tracked in the database to avoid existence checks in the storage service.

    George Claghorn

  • Deprecate service_url methods in favour of url.

    Deprecate Variant#service_url and Preview#service_url to instead use
    #url method to be consistent with Blob.

    Peter Zhu

  • Permanent URLs for public storage blobs.

    Services can be configured in config/storage.yml with a new key
    public: true | false to indicate whether a service holds public
    blobs or private blobs. Public services will always return a permanent URL.

    Deprecates Blob#service_url in favor of Blob#url.

    Peter Zhu

  • Make services aware of configuration names.

    Gannon McGibbon

  • The Content-Type header is set on image variants when they're uploaded to third-party storage services.

    Kyle Ribordy

  • Allow storage services to be configured per attachment.

    class User < ActiveRecord::Base
      has_one_attached :avatar, service: :s3
    end
    
    class Gallery < ActiveRecord::Base
      has_many_attached :photos, service: :s3
    end
    

    Dmitry Tsepelev

  • You can optionally provide a custom blob key when attaching a new file:

    user.avatar.attach key: "avatars/#{user.id}.jpg",
      io: io, content_type: "image/jpeg", filename: "avatar.jpg"
    

    Active Storage will store the blob's data on the configured service at the provided key.

    George Claghorn

  • Replace Blob.create_after_upload! with Blob.create_and_upload! and deprecate the former.

    create_after_upload! has been removed since it could lead to data
    corruption by uploading to a key on the storage service which happened to
    be already taken. Creating the record would then correctly raise a
    database uniqueness exception but the stored object would already have
    overwritten another. create_and_upload! swaps the order of operations
    so that the key gets reserved up-front or the uniqueness error gets raised,
    before the upload to a key takes place.

    Julik Tarkhanov

  • Set content disposition in direct upload using filename and disposition parameters to ActiveStorage::Service#headers_for_direct_upload.

    Peter Zhu

  • Allow record to be optionally passed to blob finders to make sharding
    easier.

    Gannon McGibbon

  • Switch from azure-storage gem to azure-storage-blob gem for Azure service.

    Peter Zhu

  • Add config.active_storage.draw_routes to disable Active Storage routes.

    Gannon McGibbon

  • Image analysis is skipped if ImageMagick returns an error.

    ActiveStorage::Analyzer::ImageAnalyzer#metadata would previously raise a
    MiniMagick::Error, which caused persistent ActiveStorage::AnalyzeJob
    failures. It now logs the error and returns {}, resulting in no metadata
    being added to the offending image blob.

    George Claghorn

  • Method calls on singular attachments return nil when no file is attached.

    Previously, assuming the following User model, user.avatar.filename would
    raise a Module::DelegationError if no avatar was attached:

    class User < ApplicationRecord
      has_one_attached :avatar
    end
    

    They now return nil.

    Matthew Tanous

  • The mirror service supports direct uploads.

    New files are directly uploaded to the primary service. When a
    directly-uploaded file is attached to a record, a background job is enqueued
    to copy it to each secondary service.

    Configure the queue used to process mirroring jobs by setting
    config.active_storage.queues.mirror. The default is :active_storage_mirror.

    George Claghorn

  • The S3 service now permits uploading files larger than 5 gigabytes.

    When uploading a file greater than 100 megabytes in size, the service
    transparently switches to multipart uploads
    using a part size computed from the file's total size and S3's part count limit.

    No application changes are necessary to take advantage of this feature. You
    can customize the default 100 MB multipart upload threshold in your S3
    service's configuration:

    production:
      service: s3
      access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
      secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
      region: us-east-1
      bucket: my-bucket
      upload:
        multipart_threshold: <%= 250.megabytes %>
    

    George Claghorn

Action Mailbox

  • Change default queue name of the incineration (:action_mailbox_incineration) and
    routing (:action_mailbox_routing) jobs to be the job adapter's default (:default).

    Rafael Mendonça França

  • Sendgrid ingress now passes through the envelope recipient as X-Original-To.

    Mark Haussmann

  • Update Mandrill inbound email route to respond appropriately to HEAD requests for URL health checks from Mandrill.

    Bill Cromie

  • Add way to deliver emails via source instead of filling out a form through the conductor interface.

    DHH

  • Mailgun ingress now passes through the envelope recipient as X-Original-To.

    Rikki Pitt

  • Deprecate Rails.application.credentials.action_mailbox.api_key and MAILGUN_INGRESS_API_KEY in favor of Rails.application.credentials.action_mailbox.signing_key and MAILGUN_INGRESS_SIGNING_KEY.

    Matthijs Vos

  • Allow easier creation of multi-part emails from the create_inbound_email_from_mail and receive_inbound_email_from_mail test helpers.

    Michael Herold

  • Fix Bcc header not being included with emails from create_inbound_email_from test helpers.

    jduff

  • Add ApplicationMailbox.mailbox_for to expose mailbox routing.

    James Dabbs

Action Text

  • Declare ActionText::FixtureSet.attachment to generate an
    <action-text-attachment sgid="..."></action-text-attachment> element with
    a valid sgid attribute.

    hello_world_review_content:
      record: hello_world (Review)
      name: content
      body: <p><%= ActionText::FixtureSet.attachment("messages", :hello_world) %> is great!</p>
    

    Sean Doyle

  • Locate fill_in_rich_text_area by <label> text

    In addition to searching for <trix-editor> elements with the appropriate
    aria-label attribute, also support locating elements that match the
    corresponding <label> element's text.

    Sean Doyle

  • Be able to add a default value to rich_text_area.

    form.rich_text_area :content, value: "<h1>Hello world</h1>"
    #=> <input type="hidden" name="message[content]" id="message_content_trix_input_message_1" value="<h1>Hello world</h1>">
    

    Paulo Ancheta

  • Add method to confirm rich text content existence by adding ? after rich
    text attribute.

    message = Message.create!(body: "<h1>Funny times!</h1>")
    message.body? #=> true
    

    Kyohei Toyoda

  • The fill_in_rich_text_area system test helper locates a Trix editor
    and fills it in with the given HTML.

    # <trix-editor id="message_content" ...></trix-editor>
    fill_in_rich_text_area "message_content", with: "Hello <em>world!</em>"
    
    # <trix-editor placeholder="Your message here" ...></trix-editor>
    fill_in_rich_text_area "Your message here", with: "Hello <em>world!</em>"
    
    # <trix-editor aria-label="Message content" ...></trix-editor>
    fill_in_rich_text_area "Message content", with: "Hello <em>world!</em>"
    
    # <input id="trix_input_1" name="message[content]" type="hidden">
    # <trix-editor input="trix_input_1"></trix-editor>
    fill_in_rich_text_area "message[content]", with: "Hello <em>world!</em>"
    

    George Claghorn

Railties

  • Added Railtie#server hook called when Rails starts a server.
    This is useful in case your application or a library needs to run
    another process next to the Rails server. This is quite common in development
    for instance to run the Webpack or the React server.

    It can be used like this:

      class MyRailtie < Rails::Railtie
        server do
          WebpackServer.run
        end
      end
    

    Edouard Chin

  • Remove deprecated rake dev:cache tasks.

    Rafael Mendonça França

  • Remove deprecated rake routes tasks.

    Rafael Mendonça França

  • Remove deprecated rake initializers tasks.

    Rafael Mendonça França

  • Remove deprecated support for using the HOST environment variable to specify the server IP.

    Rafael Mendonça França

  • Remove deprecated server argument from the rails server command.

    Rafael Mendonça França

  • Remove deprecated SOURCE_ANNOTATION_DIRECTORIES environment variable support from rails notes.

    Rafael Mendonça França

  • Remove deprecated connection option in the rails dbconsole command.

    Rafael Mendonça França

  • Remove depreated rake notes tasks.

    Rafael Mendonça França

  • Return a 405 Method Not Allowed response when a request uses an unknown HTTP method.

    Fixes #38998.

    Loren Norman

  • Make railsrc file location xdg-specification compliant

    rails new will now look for the default railsrc file at
    $XDG_CONFIG_HOME/rails/railsrc (or ~/.config/rails/railsrc if
    XDG_CONFIG_HOME is not set). If this file does not exist, rails new
    will fall back to ~/.railsrc.

    The fallback behaviour means this does not cause any breaking changes.

    Nick Wolf

  • Change the default logging level from :debug to :info to avoid inadvertent exposure of personally
    identifiable information (PII) in production environments.

    Eric M. Payne

  • Automatically generate abstract class when using multiple databases.

    When generating a scaffold for a multiple database application, Rails will now automatically generate the abstract class for the database when the database argument is passed. This abstract class will include the connection information for the writing configuration and any models generated for that database will automatically inherit from the abstract class.

    Usage:

    $ bin/rails generate scaffold Pet name:string --database=animals
    

    Will create an abstract class for the animals connection.

    class AnimalsRecord < ApplicationRecord
      self.abstract_class = true
    
      connects_to database: { writing: :animals }
    end
    

    And generate a Pet model that inherits from the new AnimalsRecord:

    class Pet < AnimalsRecord
    end
    

    If you already have an abstract class and it follows a different pattern than Rails defaults, you can pass a parent class with the database argument.

    $ bin/rails generate scaffold Pet name:string --database=animals --parent=SecondaryBase
    

    This will ensure the model inherits from the SecondaryBase parent instead of AnimalsRecord

    class Pet < SecondaryBase
    end
    

    Eileen M. Uchitelle, John Crepezzi

  • Accept params from url to prepopulate the Inbound Emails form in Rails conductor.

    Chris Oliver

  • Create a new rails app using a minimal stack.

    rails new cool_app --minimal

    All the following are excluded from your minimal stack:

    • action_cable
    • action_mailbox
    • action_mailer
    • action_text
    • active_job
    • active_storage
    • bootsnap
    • jbuilder
    • spring
    • system_tests
    • turbolinks
    • webpack

    Haroon Ahmed, DHH

  • Add default ENV variable option with BACKTRACE to turn off backtrace cleaning when debugging framework code in the
    generated config/initializers/backtrace_silencers.rb.

    BACKTRACE=1 ./bin/rails runner "MyClass.perform"

    DHH

  • The autoloading guide for Zeitwerk mode documents how to autoload classes
    during application boot in a safe way.

    Haroon Ahmed, Xavier Noria

  • The classic autoloader starts its deprecation cycle.

    New Rails projects are strongly discouraged from using classic, and we recommend that existing projects running on classic switch to zeitwerk mode when upgrading. Please check the Upgrading Ruby on Rails guide for tips.

    Xavier Noria

  • Adds rails test:all for running all tests in the test directory.

    This runs all test files in the test directory, including system tests.

    Niklas Häusele

  • Add config.generators.after_generate for processing to generated files.

    Register a callback that will get called right after generators has finished.

    Yuji Yaginuma

  • Make test file patterns configurable via Environment variables

    This makes test file patterns configurable via two environment variables:
    DEFAULT_TEST, to configure files to test, and DEFAULT_TEST_EXCLUDE,
    to configure files to exclude from testing.

    These values were hardcoded before, which made it difficult to add
    new categories of tests that should not be executed by default (e.g:
    smoke tests).

    Jorge Manrubia

  • No longer include rake rdoc task when generating plugins.

    To generate docs, use the rdoc lib command instead.

    Jonathan Hefner

  • Allow relative paths with trailing slashes to be passed to rails test.

    Eugene Kenny

  • Add rack-mini-profiler gem to the default Gemfile.

    rack-mini-profiler displays performance information such as SQL time and flame graphs.
    It's enabled by default in development environment, but can be enabled in production as well.
    See the gem README for information on how to enable it in production.

    Osama Sayegh

  • rails stats will now count TypeScript files toward JavaScript stats.

    Joshua Cody

  • Run git init when generating plugins.

    Opt out with --skip-git.

    OKURA Masafumi

  • Add benchmark generator.

    Introduce benchmark generator to benchmark Rails applications.

    rails generate benchmark opt_compare

    This creates a benchmark file that uses benchmark-ips.
    By default, two code blocks can be benchmarked using the before and after reports.

    You can run the generated benchmark file using:
    ruby script/benchmarks/opt_compare.rb

    Kevin Jalbert, Gannon McGibbon

  • Cache compiled view templates when running tests by default.

    When generating a new app without --skip-spring, caching classes is
    disabled in environments/test.rb. This implicitly disables caching
    view templates too. This change will enable view template caching by
    adding this to the generated environments/test.rb:

    config.action_view.cache_template_loading = true
    

    Jorge Manrubia

  • Introduce middleware move operations.

    With this change, you no longer need to delete and reinsert a middleware to
    move it from one place to another in the stack:

    config.middleware.move_before ActionDispatch::Flash, Magical::Unicorns
    

    This will move the Magical::Unicorns middleware before
    ActionDispatch::Flash. You can also move it after with:

    config.middleware.move_after ActionDispatch::Flash, Magical::Unicorns
    

    Genadi Samokovarov

  • Generators that inherit from NamedBase respect --force option.

    Josh Brody

  • Allow configuration of eager_load behaviour for rake environment:

    config.rake_eager_load
    

    Defaults to false as per previous behaviour.

    Thierry Joyal

  • Ensure Rails migration generator respects system-wide primary key config.

    When rails is configured to use a specific primary key type:

    config.generators do |g|
      g.orm :active_record, primary_key_type: :uuid
    end
    

    Previously:

    $ bin/rails g migration add_location_to_users location:references
    

    The references line in the migration would not have type: :uuid.
    This change causes the type to be applied appropriately.

    Louis-Michel Couture, Dermot Haughey

  • Deprecate Rails::DBConsole#config.

    Rails::DBConsole#config is deprecated without replacement. Use Rails::DBConsole.db_config.configuration_hash instead.

    Eileen M. Uchitelle, John Crepezzi

  • Rails.application.config_for merges shared configuration deeply.

    # config/example.yml
    shared:
      foo:
        bar:
          baz: 1
    development:
      foo:
        bar:
          qux: 2
    
    # Previously
    Rails.application.config_for(:example)[:foo][:bar] #=> { qux: 2 }
    
    # Now
    Rails.application.config_for(:example)[:foo][:bar] #=> { baz: 1, qux: 2 }
    

    Yuhei Kiriyama

  • Remove access to values in nested hashes returned by Rails.application.config_for via String keys.

    # config/example.yml
    development:
      options:
        key: value
    
    Rails.application.config_for(:example).options
    

    This used to return a Hash on which you could access values with String keys. This was deprecated in 6.0, and now doesn't work anymore.

    Étienne Barrié

  • Configuration files for environments (config/environments/*.rb) are
    now able to modify autoload_paths, autoload_once_paths, and
    eager_load_paths.

    As a consequence, applications cannot autoload within those files. Before, they technically could, but changes in autoloaded classes or modules had no effect anyway in the configuration because reloading does not reboot.

    Ways to use application code in these files:

    • Define early in the boot process a class that is not reloadable, from which the application takes configuration values that get passed to the framework.

      # In config/application.rb, for example.
      require "#{Rails.root}/lib/my_app/config"
      
      # In config/environments/development.rb, for example.
      config.foo = MyApp::Config.foo
      
    • If the class has to be reloadable, then wrap the configuration code in a to_prepare block:

      config.to_prepare do
        config.foo = MyModel.foo
      end
      

      That assigns the latest MyModel.foo to config.foo when the application boots, and each time there is a reload. But whether that has an effect or not depends on the configuration point, since it is not uncommon for engines to read the application configuration during initialization and set their own state from them. That process happens only on boot, not on reloads, and if that is how config.foo worked, resetting it would have no effect in the state of the engine.

    Allen Hsu & Xavier Noria

  • Support using environment variable to set pidfile.

    Ben Thorner

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 6.1.0.rc2

Active Support

  • Ensure MemoryStore disables compression by default. Reverts behavior of
    MemoryStore to its prior rails 5.1 behavior.

    Max Gurewitz

Active Model

  • No changes.

Active Record

  • Fix odd behavior of inverse_of with multiple belongs_to to same class.

    Fixes #35204.

    Tomoyuki Kai

  • Build predicate conditions with objects that delegate #id and primary key:

    class AdminAuthor
      delegate_missing_to :@author
    
      def initialize(author)
        @author = author
      end
    end
    
    Post.where(author: AdminAuthor.new(author))
    

    Sean Doyle

Action View

  • Change form_with to generate non-remote forms by default.

    form_with would generate a remote form by default. This would confuse
    users because they were forced to handle remote requests.

    All new 6.1 applications will generate non-remote forms by default.
    When upgrading a 6.0 application you can enable remote forms by default by
    setting config.action_view.form_with_generates_remote_forms to true.

    Petrik de Heus

Action Pack

  • Support for the HTTP header Feature-Policy has been revised to reflect
    its rename to Permissions-Policy.

    Rails.application.config.permissions_policy do |p|
      p.camera     :none
      p.gyroscope  :none
      p.microphone :none
      p.usb        :none
      p.fullscreen :self
      p.payment    :self, "https://secure-example.com"
    end
    

    Julien Grillot

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • Implement strict_loading on ActiveStorage associations.

    David Angulo

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 6.1.0.rc1

Active Support

  • Calling iso8601 on negative durations retains the negative sign on individual
    digits instead of prepending it.

    This change is required so we can interoperate with PostgreSQL, which prefers
    negative signs for each component.

    Compatibility with other iso8601 parsers which support leading negatives as well
    as negatives per component is still retained.

    Before:

    (-1.year - 1.day).iso8601
    # => "-P1Y1D"
    

    After:

    (-1.year - 1.day).iso8601
    # => "P-1Y-1D"
    

    Vipul A M

  • Remove deprecated ActiveSupport::Notifications::Instrumenter#end=.

    Rafael Mendonça França

  • Deprecate ActiveSupport::Multibyte::Unicode.default_normalization_form.

    Rafael Mendonça França

  • Remove deprecated ActiveSupport::Multibyte::Unicode.pack_graphemes,
    ActiveSupport::Multibyte::Unicode.unpack_graphemes,
    ActiveSupport::Multibyte::Unicode.normalize,
    ActiveSupport::Multibyte::Unicode.downcase,
    ActiveSupport::Multibyte::Unicode.upcase and ActiveSupport::Multibyte::Unicode.swapcase.

    Rafael Mendonça França

  • Remove deprecated ActiveSupport::Multibyte::Chars#consumes? and ActiveSupport::Multibyte::Chars#normalize.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/range/include_range.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/hash/transform_values.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/hash/compact.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/array/prepend_and_append.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/numeric/inquiry.

    Rafael Mendonça França

  • Remove deprecated file active_support/core_ext/module/reachable.

    Rafael Mendonça França

  • Remove deprecated Module#parent_name, Module#parent and Module#parents.

    Rafael Mendonça França

  • Remove deprecated ActiveSupport::LoggerThreadSafeLevel#after_initialize.

    Rafael Mendonça França

  • Remove deprecated LoggerSilence constant.

    Rafael Mendonça França

  • Remove deprecated fallback to I18n.default_local when config.i18n.fallbacks is empty.

    Rafael Mendonça França

  • Remove entries from local cache on RedisCacheStore#delete_matched

    Fixes #38627

    ojab

  • Speed up ActiveSupport::SecurityUtils.fixed_length_secure_compare by using
    OpenSSL.fixed_length_secure_compare, if available.

    Nate Matykiewicz

  • ActiveSupport::Cache::MemCacheStore now checks ENV["MEMCACHE_SERVERS"] before falling back to "localhost:11211" if configured without any addresses.

    config.cache_store = :mem_cache_store
    
    # is now equivalent to
    
    config.cache_store = :mem_cache_store, ENV["MEMCACHE_SERVERS"] || "localhost:11211"
    
    # instead of
    
    config.cache_store = :mem_cache_store, "localhost:11211" # ignores ENV["MEMCACHE_SERVERS"]
    

    Sam Bostock

  • ActiveSupport::Subscriber#attach_to now accepts an inherit_all: argument. When set to true,
    it allows a subscriber to receive events for methods defined in the subscriber's ancestor class(es).

    class ActionControllerSubscriber < ActiveSupport::Subscriber
      attach_to :action_controller
    
      def start_processing(event)
        info "Processing by #{event.payload[:controller]}##{event.payload[:action]} as #{format}"
      end
    
      def redirect_to(event)
        info { "Redirected to #{event.payload[:location]}" }
      end
    end
    
    # We detach ActionControllerSubscriber from the :action_controller namespace so that our CustomActionControllerSubscriber
    # can provide its own instrumentation for certain events in the namespace
    ActionControllerSubscriber.detach_from(:action_controller)
    
    class CustomActionControllerSubscriber < ActionControllerSubscriber
      attach_to :action_controller, inherit_all: true
    
      def start_processing(event)
        info "A custom response to start_processing events"
      end
    
      # => CustomActionControllerSubscriber will process events for "start_processing.action_controller" notifications
      # using its own #start_processing implementation, while retaining ActionControllerSubscriber's instrumentation
      # for "redirect_to.action_controller" notifications
    end
    

    Adrianna Chang

  • Allow the digest class used to generate non-sensitive digests to be configured with config.active_support.hash_digest_class.

    config.active_support.use_sha1_digests is deprecated in favour of config.active_support.hash_digest_class = ::Digest::SHA1.

    Dirkjan Bussink

  • Fix bug to make memcached write_entry expire correctly with unless_exist

    Jye Lee

  • Add ActiveSupport::Duration conversion methods

    in_seconds, in_minutes, in_hours, in_days, in_weeks, in_months, and in_years return the respective duration covered.

    Jason York

  • Fixed issue in ActiveSupport::Cache::RedisCacheStore not passing options
    to read_multi causing fetch_multi to not work properly

    Rajesh Sharma

  • Fixed issue in ActiveSupport::Cache::MemCacheStore which caused duplicate compression,
    and caused the provided compression_threshold to not be respected.

    Max Gurewitz

  • Prevent RedisCacheStore and MemCacheStore from performing compression
    when reading entries written with raw: true.

    Max Gurewitz

  • URI.parser is deprecated and will be removed in Rails 6.2. Use
    URI::DEFAULT_PARSER instead.

    Jean Boussier

  • require_dependency has been documented to be obsolete in :zeitwerk
    mode. The method is not deprecated as such (yet), but applications are
    encouraged to not use it.

    In :zeitwerk mode, semantics match Ruby's and you do not need to be
    defensive with load order. Just refer to classes and modules normally. If
    the constant name is dynamic, camelize if needed, and constantize.

    Xavier Noria

  • Add 3rd person aliases of Symbol#start_with? and Symbol#end_with?.

    :foo.starts_with?("f") # => true
    :foo.ends_with?("o")   # => true
    

    Ryuta Kamizono

  • Add override of unary plus for ActiveSupport::Duration.

    + 1.second is now identical to +1.second to prevent errors
    where a seemingly innocent change of formatting leads to a change in the code behavior.

    Before:

    +1.second.class
    # => ActiveSupport::Duration
    (+ 1.second).class
    # => Integer
    

    After:

    +1.second.class
    # => ActiveSupport::Duration
    (+ 1.second).class
    # => ActiveSupport::Duration
    

    Fixes #39079.

    Roman Kushnir

  • Add subsec to ActiveSupport::TimeWithZone#inspect.

    Before:

    Time.at(1498099140).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00 UTC +00:00"
    Time.at(1498099140, 123456780, :nsec).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00 UTC +00:00"
    Time.at(1498099140 + Rational("1/3")).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00 UTC +00:00"
    

    After:

    Time.at(1498099140).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00.000000000 UTC +00:00"
    Time.at(1498099140, 123456780, :nsec).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00.123456780 UTC +00:00"
    Time.at(1498099140 + Rational("1/3")).in_time_zone.inspect
    # => "Thu, 22 Jun 2017 02:39:00.333333333 UTC +00:00"
    

    akinomaeni

  • Calling ActiveSupport::TaggedLogging#tagged without a block now returns a tagged logger.

    logger.tagged("BCX").info("Funky time!") # => [BCX] Funky time!
    

    Eugene Kenny

  • Align Range#cover? extension behavior with Ruby behavior for backwards ranges.

    (1..10).cover?(5..3) now returns false, as it does in plain Ruby.

    Also update #include? and #=== behavior to match.

    Michael Groeneman

  • Update to TZInfo v2.0.0.

    This changes the output of ActiveSupport::TimeZone.utc_to_local, but
    can be controlled with the
    ActiveSupport.utc_to_local_returns_utc_offset_times config.

    New Rails 6.1 apps have it enabled by default, existing apps can upgrade
    via the config in config/initializers/new_framework_defaults_6_1.rb

    See the utc_to_local_returns_utc_offset_times documentation for details.

    Phil Ross, Jared Beck

  • Add Date and Time #yesterday? and #tomorrow? alongside #today?.

    Aliased to #prev_day? and #next_day? to match the existing #prev/next_day methods.

    Jatin Dhankhar

  • Add Enumerable#pick to complement ActiveRecord::Relation#pick.

    Eugene Kenny

  • [Breaking change] ActiveSupport::Callbacks#halted_callback_hook now receive a 2nd argument:

    ActiveSupport::Callbacks#halted_callback_hook now receive the name of the callback
    being halted as second argument.
    This change will allow you to differentiate which callbacks halted the chain
    and act accordingly.

      class Book < ApplicationRecord
        before_save { throw(:abort) }
        before_create { throw(:abort) }
    
        def halted_callback_hook(filter, callback_name)
          Rails.logger.info("Book couldn't be #{callback_name}d")
        end
    
        Book.create # => "Book couldn't be created"
        book.save # => "Book couldn't be saved"
      end
    

    Edouard Chin

  • Support prepend with ActiveSupport::Concern.

    Allows a module with extend ActiveSupport::Concern to be prepended.

    module Imposter
      extend ActiveSupport::Concern
    
      # Same as `included`, except only run when prepended.
      prepended do
      end
    end
    
    class Person
      prepend Imposter
    end
    

    Class methods are prepended to the base class, concerning is also
    updated: concerning :Imposter, prepend: true do.

    Jason Karns, Elia Schito

  • Deprecate using Range#include? method to check the inclusion of a value
    in a date time range. It is recommended to use Range#cover? method
    instead of Range#include? to check the inclusion of a value
    in a date time range.

    Vishal Telangre

  • Support added for a round_mode parameter, in all number helpers. (See: BigDecimal::mode.)

    number_to_currency(1234567890.50, precision: 0, round_mode: :half_down) # => "$1,234,567,890"
    number_to_percentage(302.24398923423, precision: 5, round_mode: :down) # => "302.24398%"
    number_to_rounded(389.32314, precision: 0, round_mode: :ceil) # => "390"
    number_to_human_size(483989, precision: 2, round_mode: :up) # => "480 KB"
    number_to_human(489939, precision: 2, round_mode: :floor) # => "480 Thousand"
    
    485000.to_s(:human, precision: 2, round_mode: :half_even) # => "480 Thousand"
    

    Tom Lord

  • Array#to_sentence no longer returns a frozen string.

    Before:

    ['one', 'two'].to_sentence.frozen?
    # => true
    

    After:

    ['one', 'two'].to_sentence.frozen?
    # => false
    

    Nicolas Dular

  • When an instance of ActiveSupport::Duration is converted to an iso8601 duration string, if weeks are mixed with date parts, the week part will be converted to days.
    This keeps the parser and serializer on the same page.

    duration = ActiveSupport::Duration.build(1000000)
    # 1 week, 4 days, 13 hours, 46 minutes, and 40.0 seconds
    
    duration_iso = duration.iso8601
    # P11DT13H46M40S
    
    ActiveSupport::Duration.parse(duration_iso)
    # 11 days, 13 hours, 46 minutes, and 40 seconds
    
    duration = ActiveSupport::Duration.build(604800)
    # 1 week
    
    duration_iso = duration.iso8601
    # P1W
    
    ActiveSupport::Duration.parse(duration_iso)
    # 1 week
    

    Abhishek Sarkar

  • Add block support to ActiveSupport::Testing::TimeHelpers#travel_back.

    Tim Masliuchenko

  • Update ActiveSupport::Messages::Metadata#fresh? to work for cookies with expiry set when
    ActiveSupport.parse_json_times = true.

    Christian Gregg

  • Support symbolic links for content_path in ActiveSupport::EncryptedFile.

    Takumi Shotoku

  • Improve Range#===, Range#include?, and Range#cover? to work with beginless (startless)
    and endless range targets.

    Allen Hsu, Andrew Hodgkinson

  • Don't use Process#clock_gettime(CLOCK_THREAD_CPUTIME_ID) on Solaris.

    Iain Beeston

  • Prevent ActiveSupport::Duration.build(value) from creating instances of
    ActiveSupport::Duration unless value is of type Numeric.

    Addresses the errant set of behaviours described in #37012 where
    ActiveSupport::Duration comparisons would fail confusingly
    or return unexpected results when comparing durations built from instances of String.

    Before:

    small_duration_from_string = ActiveSupport::Duration.build('9')
    large_duration_from_string = ActiveSupport::Duration.build('100000000000000')
    small_duration_from_int = ActiveSupport::Duration.build(9)
    
    large_duration_from_string > small_duration_from_string
    # => false
    
    small_duration_from_string == small_duration_from_int
    # => false
    
    small_duration_from_int < large_duration_from_string
    # => ArgumentError (comparison of ActiveSupport::Duration::Scalar with ActiveSupport::Duration failed)
    
    large_duration_from_string > small_duration_from_int
    # => ArgumentError (comparison of String with ActiveSupport::Duration failed)
    

    After:

    small_duration_from_string = ActiveSupport::Duration.build('9')
    # => TypeError (can't build an ActiveSupport::Duration from a String)
    

    Alexei Emam

  • Add ActiveSupport::Cache::Store#delete_multi method to delete multiple keys from the cache store.

    Peter Zhu

  • Support multiple arguments in HashWithIndifferentAccess for merge and update methods, to
    follow Ruby 2.6 addition.

    Wojciech Wnętrzak

  • Allow initializing thread_mattr_* attributes via :default option.

    class Scraper
      thread_mattr_reader :client, default: Api::Client.new
    end
    

    Guilherme Mansur

  • Add compact_blank for those times when you want to remove #blank? values from
    an Enumerable (also compact_blank! on Hash, Array, ActionController::Parameters).

    Dana Sherson

  • Make ActiveSupport::Logger Fiber-safe.

    Use Fiber.current.__id__ in ActiveSupport::Logger#local_level= in order
    to make log level local to Ruby Fibers in addition to Threads.

    Example:

    logger = ActiveSupport::Logger.new(STDOUT)
    logger.level = 1
    puts "Main is debug? #{logger.debug?}"
    
    Fiber.new {
      logger.local_level = 0
      puts "Thread is debug? #{logger.debug?}"
    }.resume
    
    puts "Main is debug? #{logger.debug?}"
    

    Before:

    Main is debug? false
    Thread is debug? true
    Main is debug? true
    

    After:

    Main is debug? false
    Thread is debug? true
    Main is debug? false
    

    Fixes #36752.

    Alexander Varnin

  • Allow the on_rotation proc used when decrypting/verifying a message to be
    passed at the constructor level.

    Before:

    crypt = ActiveSupport::MessageEncryptor.new('long_secret')
    crypt.decrypt_and_verify(encrypted_message, on_rotation: proc { ... })
    crypt.decrypt_and_verify(another_encrypted_message, on_rotation: proc { ... })
    

    After:

    crypt = ActiveSupport::MessageEncryptor.new('long_secret', on_rotation: proc { ... })
    crypt.decrypt_and_verify(encrypted_message)
    crypt.decrypt_and_verify(another_encrypted_message)
    

    Edouard Chin

  • delegate_missing_to would raise a DelegationError if the object
    delegated to was nil. Now the allow_nil option has been added to enable
    the user to specify they want nil returned in this case.

    Matthew Tanous

  • truncate would return the original string if it was too short to be truncated
    and a frozen string if it were long enough to be truncated. Now truncate will
    consistently return an unfrozen string regardless. This behavior is consistent
    with gsub and strip.

    Before:

    'foobar'.truncate(5).frozen?
    # => true
    'foobar'.truncate(6).frozen?
    # => false
    

    After:

    'foobar'.truncate(5).frozen?
    # => false
    'foobar'.truncate(6).frozen?
    # => false
    

    Jordan Thomas

Active Model

  • Pass in base instead of base_class to Error.human_attribute_name

    This is useful in cases where the human_attribute_name method depends
    on other attributes' values of the class under validation to derive what the
    attribute name should be.

    Filipe Sabella

  • Deprecate marshalling load from legacy attributes format.

    Ryuta Kamizono

  • *_previously_changed? accepts :from and :to keyword arguments like *_changed?.

    topic.update!(status: :archived)
    topic.status_previously_changed?(from: "active", to: "archived")
    # => true
    

    George Claghorn

  • Raise FrozenError when trying to write attributes that aren't backed by the database on an object that is frozen:

    class Animal
      include ActiveModel::Attributes
      attribute :age
    end
    
    animal = Animal.new
    animal.freeze
    animal.age = 25 # => FrozenError, "can't modify a frozen Animal"
    

    Josh Brody

  • Add *_previously_was attribute methods when dirty tracking. Example:

    pirate.update(catchphrase: "Ahoy!")
    pirate.previous_changes["catchphrase"] # => ["Thar She Blows!", "Ahoy!"]
    pirate.catchphrase_previously_was # => "Thar She Blows!"
    

    DHH

  • Encapsulate each validation error as an Error object.

    The ActiveModel’s errors collection is now an array of these Error
    objects, instead of messages/details hash.

    For each of these Error object, its message and full_message methods
    are for generating error messages. Its details method would return error’s
    extra parameters, found in the original details hash.

    The change tries its best at maintaining backward compatibility, however
    some edge cases won’t be covered, like errors#first will return ActiveModel::Error and manipulating
    errors.messages and errors.details hashes directly will have no effect. Moving forward,
    please convert those direct manipulations to use provided API methods instead.

    The list of deprecated methods and their planned future behavioral changes at the next major release are:

    • errors#slice! will be removed.
    • errors#each with the key, value two-arguments block will stop working, while the error single-argument block would return Error object.
    • errors#values will be removed.
    • errors#keys will be removed.
    • errors#to_xml will be removed.
    • errors#to_h will be removed, and can be replaced with errors#to_hash.
    • Manipulating errors itself as a hash will have no effect (e.g. errors[:foo] = 'bar').
    • Manipulating the hash returned by errors#messages (e.g. errors.messages[:foo] = 'bar') will have no effect.
    • Manipulating the hash returned by errors#details (e.g. errors.details[:foo].clear) will have no effect.

    lulalala

Active Record

  • Add connected_to_many API.

    This API allows applications to connect to multiple databases at once without switching all of them or implementing a deeply nested stack.

    Before:

    AnimalsRecord.connected_to(role: :reading) do
    MealsRecord.connected_to(role: :reading) do
    Dog.first # read from animals replica
    Dinner.first # read from meals replica
    Person.first # read from primary writer
    end
    end

    After:

    ActiveRecord::Base.connected_to_many([AnimalsRecord, MealsRecord], role: :reading) do
    Dog.first # read from animals replica
    Dinner.first # read from meals replica
    Person.first # read from primary writer
    end

    Eileen M. Uchitelle, John Crepezzi

  • Add option to raise or log for ActiveRecord::StrictLoadingViolationError.

    Some applications may not want to raise an error in production if using strict_loading. This would allow an application to set strict loading to log for the production environment while still raising in development and test environments.

    Set config.active_record.action_on_strict_loading_violation to :log errors instead of raising.

    Eileen M. Uchitelle

  • Allow the inverse of a has_one association that was previously autosaved to be loaded.

    Fixes #34255.

    Steven Weber

  • Optimise the length of index names for polymorphic references by using the reference name rather than the type and id column names.

    Because the default behaviour when adding an index with multiple columns is to use all column names in the index name, this could frequently lead to overly long index names for polymorphic references which would fail the migration if it exceeded the database limit.

    This change reduces the chance of that happening by using the reference name, e.g. index_my_table_on_my_reference.

    Fixes #38655.

    Luke Redpath

  • MySQL: Uniqueness validator now respects default database collation,
    no longer enforce case sensitive comparison by default.

    Ryuta Kamizono

  • Remove deprecated methods from ActiveRecord::ConnectionAdapters::DatabaseLimits.

    column_name_length
    table_name_length
    columns_per_table
    indexes_per_table
    columns_per_multicolumn_index
    sql_query_length
    joins_per_query

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_multi_insert?.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_foreign_keys_in_create?.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#supports_ranges?.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Base#update_attributes and ActiveRecord::Base#update_attributes!.

    Rafael Mendonça França

  • Remove deprecated migrations_path argument in ActiveRecord::ConnectionAdapter::SchemaStatements#assume_migrated_upto_version.

    Rafael Mendonça França

  • Remove deprecated config.active_record.sqlite3.represent_boolean_as_integer.

    Rafael Mendonça França

  • relation.create does no longer leak scope to class level querying methods
    in initialization block and callbacks.

    Before:

    User.where(name: "John").create do |john|
      User.find_by(name: "David") # => nil
    end
    

    After:

    User.where(name: "John").create do |john|
      User.find_by(name: "David") # => #<User name: "David", ...>
    end
    

    Ryuta Kamizono

  • Named scope chain does no longer leak scope to class level querying methods.

    class class User < ActiveRecord::Base
      scope :david, -> { User.where(name: "David") }
    end
    

    Before:

    User.where(name: "John").david
    # SELECT * FROM users WHERE name = 'John' AND name = 'David'
    

    After:

    User.where(name: "John").david
    # SELECT * FROM users WHERE name = 'David'
    

    Ryuta Kamizono

  • Remove deprecated methods from ActiveRecord::DatabaseConfigurations.

    fetch
    each
    first
    values
    []=

    Rafael Mendonça França

  • where.not now generates NAND predicates instead of NOR.

    Before:

     User.where.not(name: "Jon", role: "admin")
     # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
    

    After:

     User.where.not(name: "Jon", role: "admin")
     # SELECT * FROM users WHERE NOT (name == 'Jon' AND role == 'admin')
    

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Result#to_hash method.

    Rafael Mendonça França

  • Deprecate ActiveRecord::Base.allow_unsafe_raw_sql.

    Rafael Mendonça França

  • Remove deprecated support for using unsafe raw SQL in ActiveRecord::Relation methods.

    Rafael Mendonça França

  • Allow users to silence the "Rails couldn't infer whether you are using multiple databases..."
    message using config.active_record.suppress_multiple_database_warning.

    Omri Gabay

  • Connections can be granularly switched for abstract classes when connected_to is called.

    This change allows connected_to to switch a role and/or shard for a single abstract class instead of all classes globally. Applications that want to use the new feature need to set config.active_record.legacy_connection_handling to false in their application configuration.

    Example usage:

    Given an application we have a User model that inherits from ApplicationRecord and a Dog model that inherits from AnimalsRecord. AnimalsRecord and ApplicationRecord have writing and reading connections as well as shard default, one, and two.

    ActiveRecord::Base.connected_to(role: :reading) do
      User.first # reads from default replica
      Dog.first # reads from default replica
    
      AnimalsRecord.connected_to(role: :writing, shard: :one) do
        User.first # reads from default replica
        Dog.first # reads from shard one primary
      end
    
      User.first # reads from default replica
      Dog.first # reads from default replica
    
      ApplicationRecord.connected_to(role: :writing, shard: :two) do
        User.first # reads from shard two primary
        Dog.first # reads from default replica
      end
    end
    

    Eileen M. Uchitelle, John Crepezzi

  • Allow double-dash comment syntax when querying read-only databases

    James Adam

  • Add values_at method.

    Returns an array containing the values associated with the given methods.

    topic = Topic.first
    topic.values_at(:title, :author_name)
    # => ["Budget", "Jason"]
    

    Similar to Hash#values_at but on an Active Record instance.

    Guillaume Briday

  • Fix read_attribute_before_type_cast to consider attribute aliases.

    Marcelo Lauxen

  • Support passing record to uniqueness validator :conditions callable:

    class Article < ApplicationRecord
      validates_uniqueness_of :title, conditions: ->(article) {
        published_at = article.published_at
        where(published_at: published_at.beginning_of_year..published_at.end_of_year)
      }
    end
    

    Eliot Sykes

  • BatchEnumerator#update_all and BatchEnumerator#delete_all now return the
    total number of rows affected, just like their non-batched counterparts.

    Person.in_batches.update_all("first_name = 'Eugene'") # => 42
    Person.in_batches.delete_all # => 42
    

    Fixes #40287.

    Eugene Kenny

  • Add support for PostgreSQL interval data type with conversion to
    ActiveSupport::Duration when loading records from database and
    serialization to ISO 8601 formatted duration string on save.
    Add support to define a column in migrations and get it in a schema dump.
    Optional column precision is supported.

    To use this in 6.1, you need to place the next string to your model file:

    attribute :duration, :interval
    

    To keep old behavior until 6.2 is released:

    attribute :duration, :string
    

    Example:

    create_table :events do |t|
      t.string   :name
      t.interval :duration
    end
    
    class Event < ApplicationRecord
      attribute :duration, :interval
    end
    
    Event.create!(name: 'Rock Fest', duration: 2.days)
    Event.last.duration # => 2 days
    Event.last.duration.iso8601 # => "P2D"
    Event.new(duration: 'P1DT12H3S').duration # => 1 day, 12 hours, and 3 seconds
    Event.new(duration: '1 day') # Unknown value will be ignored and NULL will be written to database
    

    Andrey Novikov

  • Allow associations supporting the dependent: key to take dependent: :destroy_async.

    class Account < ActiveRecord::Base
        belongs_to :supplier, dependent: :destroy_async
    end
    

    :destroy_async will enqueue a job to destroy associated records in the background.

    DHH, George Claghorn, Cory Gwin, Rafael Mendonça França, Adrianna Chang

  • Add SKIP_TEST_DATABASE environment variable to disable modifying the test database when rails db:create and rails db:drop are called.

    Jason Schweier

  • connects_to can only be called on ActiveRecord::Base or abstract classes.

    Ensure that connects_to can only be called from ActiveRecord::Base or abstract classes. This protects the application from opening duplicate or too many connections.

    Eileen M. Uchitelle, John Crepezzi

  • All connection adapters execute now raises ActiveRecord::ConnectionNotEstablished rather than
    ActiveRecord::StatementInvalid when they encounter a connection error.

    Jean Boussier

  • Mysql2Adapter#quote_string now raises ActiveRecord::ConnectionNotEstablished rather than
    ActiveRecord::StatementInvalid when it can't connect to the MySQL server.

    Jean Boussier

  • Add support for check constraints that are NOT VALID via validate: false (PostgreSQL-only).

    Alex Robbin

  • Ensure the default configuration is considered primary or first for an environment

    If a multiple database application provides a configuration named primary, that will be treated as default. In applications that do not have a primary entry, the default database configuration will be the first configuration for an environment.

    Eileen M. Uchitelle

  • Allow where references association names as joined table name aliases.

    class Comment < ActiveRecord::Base
      enum label: [:default, :child]
      has_many :children, class_name: "Comment", foreign_key: :parent_id
    end
    
    # ... FROM comments LEFT OUTER JOIN comments children ON ... WHERE children.label = 1
    Comment.includes(:children).where("children.label": "child")
    

    Ryuta Kamizono

  • Support storing demodulized class name for polymorphic type.

    Before Rails 6.1, storing demodulized class name is supported only for STI type
    by store_full_sti_class class attribute.

    Now store_full_class_name class attribute can handle both STI and polymorphic types.

    Ryuta Kamizono

  • Deprecate rails db:structure:{load, dump} tasks and extend
    rails db:schema:{load, dump} tasks to work with either :ruby or :sql format,
    depending on config.active_record.schema_format configuration value.

    fatkodima

  • Respect the select values for eager loading.

    post = Post.select("UPPER(title) AS title").first
    post.title # => "WELCOME TO THE WEBLOG"
    post.body  # => ActiveModel::MissingAttributeError
    
    # Rails 6.0 (ignore the `select` values)
    post = Post.select("UPPER(title) AS title").eager_load(:comments).first
    post.title # => "Welcome to the weblog"
    post.body  # => "Such a lovely day"
    
    # Rails 6.1 (respect the `select` values)
    post = Post.select("UPPER(title) AS title").eager_load(:comments).first
    post.title # => "WELCOME TO THE WEBLOG"
    post.body  # => ActiveModel::MissingAttributeError
    

    Ryuta Kamizono

  • Allow attribute's default to be configured but keeping its own type.

    class Post < ActiveRecord::Base
      attribute :written_at, default: -> { Time.now.utc }
    end
    
    # Rails 6.0
    Post.type_for_attribute(:written_at) # => #<Type::Value ... precision: nil, ...>
    
    # Rails 6.1
    Post.type_for_attribute(:written_at) # => #<Type::DateTime ... precision: 6, ...>
    

    Ryuta Kamizono

  • Allow default to be configured for Enum.

    class Book < ActiveRecord::Base
      enum status: [:proposed, :written, :published], _default: :published
    end
    
    Book.new.status # => "published"
    

    Ryuta Kamizono

  • Deprecate YAML loading from legacy format older than Rails 5.0.

    Ryuta Kamizono

  • Added the setting ActiveRecord::Base.immutable_strings_by_default, which
    allows you to specify that all string columns should be frozen unless
    otherwise specified. This will reduce memory pressure for applications which
    do not generally mutate string properties of Active Record objects.

    Sean Griffin, Ryuta Kamizono

  • Deprecate map! and collect! on ActiveRecord::Result.

    Ryuta Kamizono

  • Support relation.and for intersection as Set theory.

    david_and_mary = Author.where(id: [david, mary])
    mary_and_bob   = Author.where(id: [mary, bob])
    
    david_and_mary.merge(mary_and_bob) # => [mary, bob]
    
    david_and_mary.and(mary_and_bob) # => [mary]
    david_and_mary.or(mary_and_bob)  # => [david, mary, bob]
    

    Ryuta Kamizono

  • Merging conditions on the same column no longer maintain both conditions,
    and will be consistently replaced by the latter condition in Rails 6.2.
    To migrate to Rails 6.2's behavior, use relation.merge(other, rewhere: true).

    # Rails 6.1 (IN clause is replaced by merger side equality condition)
    Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
    
    # Rails 6.1 (both conflict conditions exists, deprecated)
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
    
    # Rails 6.1 with rewhere to migrate to Rails 6.2's behavior
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
    
    # Rails 6.2 (same behavior with IN clause, mergee side condition is consistently replaced)
    Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
    Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
    

    Ryuta Kamizono

  • Do not mark Postgresql MAC address and UUID attributes as changed when the assigned value only varies by case.

    Peter Fry

  • Resolve issue with insert_all unique_by option when used with expression index.

    When the :unique_by option of ActiveRecord::Persistence.insert_all and
    ActiveRecord::Persistence.upsert_all was used with the name of an expression index, an error
    was raised. Adding a guard around the formatting behavior for the :unique_by corrects this.

    Usage:

    create_table :books, id: :integer, force: true do |t|
      t.column :name, :string
      t.index "lower(name)", unique: true
    end
    
    Book.insert_all [{ name: "MyTest" }], unique_by: :index_books_on_lower_name
    

    Fixes #39516.

    Austen Madden

  • Add basic support for CHECK constraints to database migrations.

    Usage:

    add_check_constraint :products, "price > 0", name: "price_check"
    remove_check_constraint :products, name: "price_check"
    

    fatkodima

  • Add ActiveRecord::Base.strict_loading_by_default and ActiveRecord::Base.strict_loading_by_default=
    to enable/disable strict_loading mode by default for a model. The configuration's value is
    inheritable by subclasses, but they can override that value and it will not impact parent class.

    Usage:

    class Developer < ApplicationRecord
      self.strict_loading_by_default = true
    
      has_many :projects
    end
    
    dev = Developer.first
    dev.projects.first
    # => ActiveRecord::StrictLoadingViolationError Exception: Developer is marked as strict_loading and Project cannot be lazily loaded.
    

    bogdanvlviv

  • Deprecate passing an Active Record object to quote/type_cast directly.

    Ryuta Kamizono

  • Default engine ENGINE=InnoDB is no longer dumped to make schema more agnostic.

    Before:

    create_table "accounts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
    end
    

    After:

    create_table "accounts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
    end
    

    Ryuta Kamizono

  • Added delegated type as an alternative to single-table inheritance for representing class hierarchies.
    See ActiveRecord::DelegatedType for the full description.

    DHH

  • Deprecate aggregations with group by duplicated fields.

    To migrate to Rails 6.2's behavior, use uniq!(:group) to deduplicate group fields.

    accounts = Account.group(:firm_id)
    
    # duplicated group fields, deprecated.
    accounts.merge(accounts.where.not(credit_limit: nil)).sum(:credit_limit)
    # => {
    #   [1, 1] => 50,
    #   [2, 2] => 60
    # }
    
    # use `uniq!(:group)` to deduplicate group fields.
    accounts.merge(accounts.where.not(credit_limit: nil)).uniq!(:group).sum(:credit_limit)
    # => {
    #   1 => 50,
    #   2 => 60
    # }
    

    Ryuta Kamizono

  • Deprecate duplicated query annotations.

    To migrate to Rails 6.2's behavior, use uniq!(:annotate) to deduplicate query annotations.

    accounts = Account.where(id: [1, 2]).annotate("david and mary")
    
    # duplicated annotations, deprecated.
    accounts.merge(accounts.rewhere(id: 3))
    # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */ /* david and mary */
    
    # use `uniq!(:annotate)` to deduplicate annotations.
    accounts.merge(accounts.rewhere(id: 3)).uniq!(:annotate)
    # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */
    

    Ryuta Kamizono

  • Resolve conflict between counter cache and optimistic locking.

    Bump an Active Record instance's lock version after updating its counter
    cache. This avoids raising an unnecessary ActiveRecord::StaleObjectError
    upon subsequent transactions by maintaining parity with the corresponding
    database record's lock_version column.

    Fixes #16449.

    Aaron Lipman

  • Support merging option :rewhere to allow mergee side condition to be replaced exactly.

    david_and_mary = Author.where(id: david.id..mary.id)
    
    # both conflict conditions exists
    david_and_mary.merge(Author.where(id: bob)) # => []
    
    # mergee side condition is replaced by rewhere
    david_and_mary.merge(Author.rewhere(id: bob)) # => [bob]
    
    # mergee side condition is replaced by rewhere option
    david_and_mary.merge(Author.where(id: bob), rewhere: true) # => [bob]
    

    Ryuta Kamizono

  • Add support for finding records based on signed ids, which are tamper-proof, verified ids that can be
    set to expire and scoped with a purpose. This is particularly useful for things like password reset
    or email verification, where you want the bearer of the signed id to be able to interact with the
    underlying record, but usually only within a certain time period.

    signed_id = User.first.signed_id expires_in: 15.minutes, purpose: :password_reset
    
    User.find_signed signed_id # => nil, since the purpose does not match
    
    travel 16.minutes
    User.find_signed signed_id, purpose: :password_reset # => nil, since the signed id has expired
    
    travel_back
    User.find_signed signed_id, purpose: :password_reset # => User.first
    
    User.find_signed! "bad data" # => ActiveSupport::MessageVerifier::InvalidSignature
    

    DHH

  • Support ALGORITHM = INSTANT DDL option for index operations on MySQL.

    Ryuta Kamizono

  • Fix index creation to preserve index comment in bulk change table on MySQL.

    Ryuta Kamizono

  • Allow unscope to be aware of table name qualified values.

    It is possible to unscope only the column in the specified table.

    posts = Post.joins(:comments).group(:"posts.hidden")
    posts = posts.where("posts.hidden": false, "comments.hidden": false)
    
    posts.count
    # => { false => 10 }
    
    # unscope both hidden columns
    posts.unscope(where: :hidden).count
    # => { false => 11, true => 1 }
    
    # unscope only comments.hidden column
    posts.unscope(where: :"comments.hidden").count
    # => { false => 11 }
    

    Ryuta Kamizono, Slava Korolev

  • Fix rewhere to truly overwrite collided where clause by new where clause.

    steve = Person.find_by(name: "Steve")
    david = Author.find_by(name: "David")
    
    relation = Essay.where(writer: steve)
    
    # Before
    relation.rewhere(writer: david).to_a # => []
    
    # After
    relation.rewhere(writer: david).to_a # => [david]
    

    Ryuta Kamizono

  • Inspect time attributes with subsec.

    p Knot.create
    => #<Knot id: 1, created_at: "2016-05-05 01:29:47.116928000">
    

    akinomaeni

  • Deprecate passing a column to type_cast.

    Ryuta Kamizono

  • Deprecate in_clause_length and allowed_index_name_length in DatabaseLimits.

    Ryuta Kamizono

  • Support bulk insert/upsert on relation to preserve scope values.

    Josef Šimánek, Ryuta Kamizono

  • Preserve column comment value on changing column name on MySQL.

    Islam Taha

  • Add support for if_exists option for removing an index.

    The remove_index method can take an if_exists option. If this is set to true an error won't be raised if the index doesn't exist.

    Eileen M. Uchitelle

  • Remove ibm_db, informix, mssql, oracle, and oracle12 Arel visitors which are not used in the code base.

    Ryuta Kamizono

  • Prevent build_association from touching a parent record if the record isn't persisted for has_one associations.

    Fixes #38219.

    Josh Brody

  • Add support for if_not_exists option for adding index.

    The add_index method respects if_not_exists option. If it is set to true
    index won't be added.

    Usage:

      add_index :users, :account_id, if_not_exists: true
    

    The if_not_exists option passed to create_table also gets propagated to indexes
    created within that migration so that if table and its indexes exist then there is no
    attempt to create them again.

    Prathamesh Sonpatki

  • Add ActiveRecord::Base#previously_new_record? to show if a record was new before the last save.

    Tom Ward

  • Support descending order for find_each, find_in_batches, and in_batches.

    Batch processing methods allow you to work with the records in batches, greatly reducing memory consumption, but records are always batched from oldest id to newest.

    This change allows reversing the order, batching from newest to oldest. This is useful when you need to process newer batches of records first.

    Pass order: :desc to yield batches in descending order. The default remains order: :asc.

    Person.find_each(order: :desc) do |person|
      person.party_all_night!
    end
    

    Alexey Vasiliev

  • Fix insert_all with enum values.

    Fixes #38716.

    Joel Blum

  • Add support for db:rollback:name for multiple database applications.

    Multiple database applications will now raise if db:rollback is call and recommend using the db:rollback:[NAME] to rollback migrations.

    Eileen M. Uchitelle

  • Relation#pick now uses already loaded results instead of making another query.

    Eugene Kenny

  • Deprecate using return, break or throw to exit a transaction block after writes.

    Dylan Thacker-Smith

  • Dump the schema or structure of a database when calling db:migrate:name.

    In previous versions of Rails, rails db:migrate would dump the schema of the database. In Rails 6, that holds true (rails db:migrate dumps all databases' schemas), but rails db:migrate:name does not share that behavior.

    Going forward, calls to rails db:migrate:name will dump the schema (or structure) of the database being migrated.

    Kyle Thompson

  • Reset the ActiveRecord::Base connection after rails db:migrate:name.

    When rails db:migrate has finished, it ensures the ActiveRecord::Base connection is reset to its original configuration. Going forward, rails db:migrate:name will have the same behavior.

    Kyle Thompson

  • Disallow calling connected_to on subclasses of ActiveRecord::Base.

    Behavior has not changed here but the previous API could be misleading to people who thought it would switch connections for only that class. connected_to switches the context from which we are getting connections, not the connections themselves.

    Eileen M. Uchitelle, John Crepezzi

  • Add support for horizontal sharding to connects_to and connected_to.

    Applications can now connect to multiple shards and switch between their shards in an application. Note that the shard swapping is still a manual process as this change does not include an API for automatic shard swapping.

    Usage:

    Given the following configuration:

    # config/database.yml
    production:
      primary:
        database: my_database
      primary_shard_one:
        database: my_database_shard_one
    

    Connect to multiple shards:

    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    
      connects_to shards: {
        default: { writing: :primary },
        shard_one: { writing: :primary_shard_one }
      }
    

    Swap between shards in your controller / model code:

    ActiveRecord::Base.connected_to(shard: :shard_one) do
      # Read from shard one
    end
    

    The horizontal sharding API also supports read replicas. See guides for more details.

    Eileen M. Uchitelle, John Crepezzi

  • Deprecate spec_name in favor of name on database configurations.

    The accessors for spec_name on configs_for and DatabaseConfig are deprecated. Please use name instead.

    Deprecated behavior:

    db_config = ActiveRecord::Base.configs_for(env_name: "development", spec_name: "primary")
    db_config.spec_name
    

    New behavior:

    db_config = ActiveRecord::Base.configs_for(env_name: "development", name: "primary")
    db_config.name
    

    Eileen M. Uchitelle

  • Add additional database-specific rake tasks for multi-database users.

    Previously, rails db:create, rails db:drop, and rails db:migrate were the only rails tasks that could operate on a single
    database. For example:

    rails db:create
    rails db:create:primary
    rails db:create:animals
    rails db:drop
    rails db:drop:primary
    rails db:drop:animals
    rails db:migrate
    rails db:migrate:primary
    rails db:migrate:animals
    

    With these changes, rails db:schema:dump, rails db:schema:load, rails db:structure:dump, rails db:structure:load and
    rails db:test:prepare can additionally operate on a single database. For example:

    rails db:schema:dump
    rails db:schema:dump:primary
    rails db:schema:dump:animals
    rails db:schema:load
    rails db:schema:load:primary
    rails db:schema:load:animals
    rails db:structure:dump
    rails db:structure:dump:primary
    rails db:structure:dump:animals
    rails db:structure:load
    rails db:structure:load:primary
    rails db:structure:load:animals
    rails db:test:prepare
    rails db:test:prepare:primary
    rails db:test:prepare:animals
    

    Kyle Thompson

  • Add support for strict_loading mode on association declarations.

    Raise an error if attempting to load a record from an association that has been marked as strict_loading unless it was explicitly eager loaded.

    Usage:

    class Developer < ApplicationRecord
      has_many :projects, strict_loading: true
    end
    
    dev = Developer.first
    dev.projects.first
    # => ActiveRecord::StrictLoadingViolationError: The projects association is marked as strict_loading and cannot be lazily loaded.
    

    Kevin Deisz

  • Add support for strict_loading mode to prevent lazy loading of records.

    Raise an error if a parent record is marked as strict_loading and attempts to lazily load its associations. This is useful for finding places you may want to preload an association and avoid additional queries.

    Usage:

    dev = Developer.strict_loading.first
    dev.audit_logs.to_a
    # => ActiveRecord::StrictLoadingViolationError: Developer is marked as strict_loading and AuditLog cannot be lazily loaded.
    

    Eileen M. Uchitelle, Aaron Patterson

  • Add support for PostgreSQL 11+ partitioned indexes when using upsert_all.

    Sebastián Palma

  • Adds support for if_not_exists to add_column and if_exists to remove_column.

    Applications can set their migrations to ignore exceptions raised when adding a column that already exists or when removing a column that does not exist.

    Example Usage:

    class AddColumnTitle < ActiveRecord::Migration[6.1]
      def change
        add_column :posts, :title, :string, if_not_exists: true
      end
    end
    
    class RemoveColumnTitle < ActiveRecord::Migration[6.1]
      def change
        remove_column :posts, :title, if_exists: true
      end
    end
    

    Eileen M. Uchitelle

  • Regexp-escape table name for MS SQL Server.

    Add Regexp.escape to one method in ActiveRecord, so that table names with regular expression characters in them work as expected. Since MS SQL Server uses "[" and "]" to quote table and column names, and those characters are regular expression characters, methods like pluck and select fail in certain cases when used with the MS SQL Server adapter.

    Larry Reid

  • Store advisory locks on their own named connection.

    Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped.

    In order to fix this we are storing the advisory lock on a new connection with the connection specification name AdvisoryLockBase. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this.

    Eileen M. Uchitelle, John Crepezzi

  • Allow schema cache path to be defined in the database configuration file.

    For example:

    development:
      adapter: postgresql
      database: blog_development
      pool: 5
      schema_cache_path: tmp/schema/main.yml
    

    Katrina Owen

  • Deprecate #remove_connection in favor of #remove_connection_pool when called on the handler.

    #remove_connection is deprecated in order to support returning a DatabaseConfig object instead of a Hash. Use #remove_connection_pool, #remove_connection will be removed in 6.2.

    Eileen M. Uchitelle, John Crepezzi

  • Deprecate #default_hash and it's alias #[] on database configurations.

    Applications should use configs_for. #default_hash and #[] will be removed in 6.2.

    Eileen M. Uchitelle, John Crepezzi

  • Add scale support to ActiveRecord::Validations::NumericalityValidator.

    Gannon McGibbon

  • Find orphans by looking for missing relations through chaining where.missing:

    Before:

    Post.left_joins(:author).where(authors: { id: nil })
    

    After:

    Post.where.missing(:author)
    

    Tom Rossi

  • Ensure :reading connections always raise if a write is attempted.

    Now Rails will raise an ActiveRecord::ReadOnlyError if any connection on the reading handler attempts to make a write. If your reading role needs to write you should name the role something other than :reading.

    Eileen M. Uchitelle

  • Deprecate "primary" as the connection_specification_name for ActiveRecord::Base.

    "primary" has been deprecated as the connection_specification_name for ActiveRecord::Base in favor of using "ActiveRecord::Base". This change affects calls to ActiveRecord::Base.connection_handler.retrieve_connection and ActiveRecord::Base.connection_handler.remove_connection. If you're calling these methods with "primary", please switch to "ActiveRecord::Base".

    Eileen M. Uchitelle, John Crepezzi

  • Add ActiveRecord::Validations::NumericalityValidator with
    support for casting floats using a database columns' precision value.

    Gannon McGibbon

  • Enforce fresh ETag header after a collection's contents change by adding
    ActiveRecord::Relation#cache_key_with_version. This method will be used by
    ActionController::ConditionalGet to ensure that when collection cache versioning
    is enabled, requests using ConditionalGet don't return the same ETag header
    after a collection is modified.

    Fixes #38078.

    Aaron Lipman

  • Skip test database when running db:create or db:drop in development
    with DATABASE_URL set.

    Brian Buchalter

  • Don't allow mutations on the database configurations hash.

    Freeze the configurations hash to disallow directly changing it. If applications need to change the hash, for example to create databases for parallelization, they should use the DatabaseConfig object directly.

    Before:

    @db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary")
    @db_config.configuration_hash.merge!(idle_timeout: "0.02")
    

    After:

    @db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary")
    config = @db_config.configuration_hash.merge(idle_timeout: "0.02")
    db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(@db_config.env_name, @db_config.spec_name, config)
    

    Eileen M. Uchitelle, John Crepezzi

  • Remove :connection_id from the sql.active_record notification.

    Aaron Patterson, Rafael Mendonça França

  • The :name key will no longer be returned as part of DatabaseConfig#configuration_hash. Please use DatabaseConfig#owner_name instead.

    Eileen M. Uchitelle, John Crepezzi

  • ActiveRecord's belongs_to_required_by_default flag can now be set per model.

    You can now opt-out/opt-in specific models from having their associations required
    by default.

    This change is meant to ease the process of migrating all your models to have
    their association required.

    Edouard Chin

  • The connection_config method has been deprecated, please use connection_db_config instead which will return a DatabaseConfigurations::DatabaseConfig instead of a Hash.

    Eileen M. Uchitelle, John Crepezzi

  • Retain explicit selections on the base model after applying includes and joins.

    Resolves #34889.

    Patrick Rebsch

  • The database kwarg is deprecated without replacement because it can't be used for sharding and creates an issue if it's used during a request. Applications that need to create new connections should use connects_to instead.

    Eileen M. Uchitelle, John Crepezzi

  • Allow attributes to be fetched from Arel node groupings.

    Jeff Emminger, Gannon McGibbon

  • A database URL can now contain a querystring value that contains an equal sign. This is needed to support passing PostgreSQL options.

    Joshua Flanagan

  • Calling methods like establish_connection with a Hash which is invalid (eg: no adapter) will now raise an error the same way as connections defined in config/database.yml.

    John Crepezzi

  • Specifying implicit_order_column now subsorts the records by primary key if available to ensure deterministic results.

    Paweł Urbanek

  • where(attr => []) now loads an empty result without making a query.

    John Hawthorn

  • Fixed the performance regression for primary_keys introduced MySQL 8.0.

    Hiroyuki Ishii

  • Add support for belongs_to to has_many inversing.

    Gannon McGibbon

  • Allow length configuration for has_secure_token method. The minimum length
    is set at 24 characters.

    Before:

    has_secure_token :auth_token
    

    After:

    has_secure_token :default_token             # 24 characters
    has_secure_token :auth_token, length: 36    # 36 characters
    has_secure_token :invalid_token, length: 12 # => ActiveRecord::SecureToken::MinimumLengthError
    

    Bernardo de Araujo

  • Deprecate DatabaseConfigurations#to_h. These connection hashes are still available via ActiveRecord::Base.configurations.configs_for.

    Eileen Uchitelle, John Crepezzi

  • Add DatabaseConfig#configuration_hash to return database configuration hashes with symbol keys, and use all symbol-key configuration hashes internally. Deprecate DatabaseConfig#config which returns a String-keyed Hash with the same values.

    John Crepezzi, Eileen Uchitelle

  • Allow column names to be passed to remove_index positionally along with other options.

    Passing other options can be necessary to make remove_index correctly reversible.

    Before:

    add_index    :reports, :report_id               # => works
    add_index    :reports, :report_id, unique: true # => works
    remove_index :reports, :report_id               # => works
    remove_index :reports, :report_id, unique: true # => ArgumentError
    

    After:

    remove_index :reports, :report_id, unique: true # => works
    

    Eugene Kenny

  • Allow bulk ALTER statements to drop and recreate indexes with the same name.

    Eugene Kenny

  • insert, insert_all, upsert, and upsert_all now clear the query cache.

    Eugene Kenny

  • Call while_preventing_writes directly from connected_to.

    In some cases application authors want to use the database switching middleware and make explicit calls with connected_to. It's possible for an app to turn off writes and not turn them back on by the time we call connected_to(role: :writing).

    This change allows apps to fix this by assuming if a role is writing we want to allow writes, except in the case it's explicitly turned off.

    Eileen M. Uchitelle

  • Improve detection of ActiveRecord::StatementTimeout with mysql2 adapter in the edge case when the query is terminated during filesort.

    Kir Shatrov

  • Stop trying to read yaml file fixtures when loading Active Record fixtures.

    Gannon McGibbon

  • Deprecate .reorder(nil) with .first / .first! taking non-deterministic result.

    To continue taking non-deterministic result, use .take / .take! instead.

    Ryuta Kamizono

  • Preserve user supplied joins order as much as possible.

    Fixes #36761, #34328, #24281, #12953.

    Ryuta Kamizono

  • Allow matches_regex and does_not_match_regexp on the MySQL Arel visitor.

    James Pearson

  • Allow specifying fixtures to be ignored by setting ignore in YAML file's '_fixture' section.

    Tongfei Gao

  • Make the DATABASE_URL env variable only affect the primary connection. Add new env variables for multiple databases.

    John Crepezzi, Eileen Uchitelle

  • Add a warning for enum elements with 'not_' prefix.

    class Foo
      enum status: [:sent, :not_sent]
    end
    

    Edu Depetris

  • Make currency symbols optional for money column type in PostgreSQL.

    Joel Schneider

  • Add support for beginless ranges, introduced in Ruby 2.7.

    Josh Goodall

  • Add database_exists? method to connection adapters to check if a database exists.

    Guilherme Mansur

  • Loading the schema for a model that has no table_name raises a TableNotSpecified error.

    Guilherme Mansur, Eugene Kenny

  • PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.

    Fixes #36022.

    Ryuta Kamizono

  • Make ActiveRecord ConnectionPool.connections method thread-safe.

    Fixes #36465.

    Jeff Doering

  • Add support for multiple databases to rails db:abort_if_pending_migrations.

    Mark Lee

  • Fix sqlite3 collation parsing when using decimal columns.

    Martin R. Schuster

  • Fix invalid schema when primary key column has a comment.

    Fixes #29966.

    Guilherme Goettems Schneider

  • Fix table comment also being applied to the primary key column.

    Guilherme Goettems Schneider

  • Allow generated create_table migrations to include or skip timestamps.

    Michael Duchemin

Action View

  • Yield translated strings to calls of ActionView::FormBuilder#button
    when a block is given.

    Sean Doyle

  • Alias ActionView::Helpers::Tags::Label::LabelBuilder#translation to
    #to_s so that form.label calls can yield that value to their blocks.

    Sean Doyle

  • Rename the new TagHelper#class_names method to TagHelper#token_list,
    and make the original available as an alias.

    token_list("foo", "foo bar")
    # => "foo bar"
    

    Sean Doyle

  • ARIA Array and Hash attributes are treated as space separated DOMTokenList
    values. This is useful when declaring lists of label text identifiers in
    aria-labelledby or aria-describedby.

    tag.input type: 'checkbox', name: 'published', aria: {
      invalid: @post.errors[:published].any?,
      labelledby: ['published_context', 'published_label'],
      describedby: { published_errors: @post.errors[:published].any? }
    }
    #=> <input
          type="checkbox" name="published" aria-invalid="true"
          aria-labelledby="published_context published_label"
          aria-describedby="published_errors"
        >
    

    Sean Doyle

  • Remove deprecated escape_whitelist from ActionView::Template::Handlers::ERB.

    Rafael Mendonça França

  • Remove deprecated find_all_anywhere from ActionView::Resolver.

    Rafael Mendonça França

  • Remove deprecated formats from ActionView::Template::HTML.

    Rafael Mendonça França

  • Remove deprecated formats from ActionView::Template::RawFile.

    Rafael Mendonça França

  • Remove deprecated formats from ActionView::Template::Text.

    Rafael Mendonça França

  • Remove deprecated find_file from ActionView::PathSet.

    Rafael Mendonça França

  • Remove deprecated rendered_format from ActionView::LookupContext.

    Rafael Mendonça França

  • Remove deprecated find_file from ActionView::ViewPaths.

    Rafael Mendonça França

  • Require that ActionView::Base subclasses implement #compiled_method_container.

    Rafael Mendonça França

  • Remove deprecated support to pass an object that is not a ActionView::LookupContext as the first argument
    in ActionView::Base#initialize.

    Rafael Mendonça França

  • Remove deprecated format argument ActionView::Base#initialize.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#refresh.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#original_encoding.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#variants.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#formats.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#virtual_path=.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template#updated_at.

    Rafael Mendonça França

  • Remove deprecated updated_at argument required on ActionView::Template#initialize.

    Rafael Mendonça França

  • Make locals argument required on ActionView::Template#initialize.

    Rafael Mendonça França

  • Remove deprecated ActionView::Template.finalize_compiled_template_methods.

    Rafael Mendonça França

  • Remove deprecated config.action_view.finalize_compiled_template_methods

    Rafael Mendonça França

  • Remove deprecated support to calling ActionView::ViewPaths#with_fallback with a block.

    Rafael Mendonça França

  • Remove deprecated support to passing absolute paths to render template:.

    Rafael Mendonça França

  • Remove deprecated support to passing relative paths to render file:.

    Rafael Mendonça França

  • Remove support to template handlers that don't accept two arguments.

    Rafael Mendonça França

  • Remove deprecated pattern argument in ActionView::Template::PathResolver.

    Rafael Mendonça França

  • Remove deprecated support to call private methods from object in some view helpers.

    Rafael Mendonça França

  • ActionView::Helpers::TranslationHelper#translate accepts a block, yielding
    the translated text and the fully resolved translation key:

    <%= translate(".relative_key") do |translation, resolved_key| %>
      <span title="<%= resolved_key %>"><%= translation %></span>
    <% end %>
    

    Sean Doyle

  • Ensure cache fragment digests include all relevant template dependencies when
    fragments are contained in a block passed to the render helper. Remove the
    virtual_path keyword arguments found in CacheHelper as they no longer possess
    any function following 1581cab.

    Fixes #38984.

    Aaron Lipman

  • Deprecate config.action_view.raise_on_missing_translations in favor of
    config.i18n.raise_on_missing_translations.

    New generalized configuration option now determines whether an error should be raised
    for missing translations in controllers and views.

    fatkodima

  • Instrument layout rendering in TemplateRenderer#render_with_layout as render_layout.action_view,
    and include (when necessary) the layout's virtual path in notification payloads for collection and partial renders.

    Zach Kemp

  • ActionView::Base.annotate_rendered_view_with_filenames annotates HTML output with template file names.

    Joel Hawksley, Aaron Patterson

  • ActionView::Helpers::TranslationHelper#translate returns nil when
    passed default: nil without a translation matching I18n#translate.

    Stefan Wrobel

  • OptimizedFileSystemResolver prefers template details in order of locale,
    formats, variants, handlers.

    Iago Pimenta

  • Added class_names helper to create a CSS class value with conditional classes.

    Joel Hawksley, Aaron Patterson

  • Add support for conditional values to TagBuilder.

    Joel Hawksley

  • ActionView::Helpers::FormOptionsHelper#select should mark option for nil as selected.

    @post = Post.new
    @post.category = nil
    
    # Before
    select("post", "category", none: nil, programming: 1, economics: 2)
    # =>
    # <select name="post[category]" id="post_category">
    #   <option value="">none</option>
    #  <option value="1">programming</option>
    #  <option value="2">economics</option>
    # </select>
    
    # After
    select("post", "category", none: nil, programming: 1, economics: 2)
    # =>
    # <select name="post[category]" id="post_category">
    #   <option selected="selected" value="">none</option>
    #  <option value="1">programming</option>
    #  <option value="2">economics</option>
    # </select>
    

    bogdanvlviv

  • Log lines for partial renders and started template renders are now
    emitted at the DEBUG level instead of INFO.

    Completed template renders are still logged at the INFO level.

    DHH

  • ActionView::Helpers::SanitizeHelper: support rails-html-sanitizer 1.1.0.

    Juanito Fatas

  • Added phone_to helper method to create a link from mobile numbers.

    Pietro Moro

  • annotated_source_code returns an empty array so TemplateErrors without a
    template in the backtrace are surfaced properly by DebugExceptions.

    Guilherme Mansur, Kasper Timm Hansen

  • Add autoload for SyntaxErrorInTemplate so syntax errors are correctly raised by DebugExceptions.

    Guilherme Mansur, Gannon McGibbon

  • RenderingHelper supports rendering objects that respond_to? :render_in.

    Joel Hawksley, Natasha Umer, Aaron Patterson, Shawn Allen, Emily Plummer, Diana Mounter, John Hawthorn, Nathan Herald, Zaid Zawaideh, Zach Ahn

  • Fix select_tag so that it doesn't change options when include_blank is present.

    Younes SERRAJ

Action Pack

  • Allow ActionDispatch::HostAuthorization to exclude specific requests.

    Host Authorization checks can be skipped for specific requests. This allows for health check requests to be permitted for requests with missing or non-matching host headers.

    Chris Bisnett

  • Add config.action_dispatch.request_id_header to allow changing the name of
    the unique X-Request-Id header

    Arlston Fernandes

  • Deprecate config.action_dispatch.return_only_media_type_on_content_type.

    Rafael Mendonça França

  • Change ActionDispatch::Response#content_type to return the full Content-Type header.

    Rafael Mendonça França

  • Remove deprecated ActionDispatch::Http::ParameterFilter.

    Rafael Mendonça França

  • Added support for exclusive no-store Cache-Control header.

    If no-store is set on Cache-Control header it is exclusive (all other cache directives are dropped).

    Chris Kruger

  • Catch invalid UTF-8 parameters for POST requests and respond with BadRequest.

    Additionally, perform #set_binary_encoding in ActionDispatch::Http::Request#GET and
    ActionDispatch::Http::Request#POST prior to validating encoding.

    Adrianna Chang

  • Allow assert_recognizes routing assertions to work on mounted root routes.

    Gannon McGibbon

  • Change default redirection status code for non-GET/HEAD requests to 308 Permanent Redirect for ActionDispatch::SSL.

    Alan Tan, Oz Ben-David

  • Fix follow_redirect! to follow redirection with same HTTP verb when following
    a 308 redirection.

    Alan Tan

  • When multiple domains are specified for a cookie, a domain will now be
    chosen only if it is equal to or is a superdomain of the request host.

    Jonathan Hefner

  • ActionDispatch::Static handles precompiled Brotli (.br) files.

    Adds to existing support for precompiled gzip (.gz) files.
    Brotli files are preferred due to much better compression.

    When the browser requests /some.js with Accept-Encoding: br,
    we check for public/some.js.br and serve that file, if present, with
    Content-Encoding: br and Vary: Accept-Encoding headers.

    Ryan Edward Hall, Jeremy Daer

  • Add raise_on_missing_translations support for controllers.

    This configuration determines whether an error should be raised for missing translations.
    It can be enabled through config.i18n.raise_on_missing_translations. Note that described
    configuration also affects raising error for missing translations in views.

    fatkodima

  • Added compact and compact! to ActionController::Parameters.

    Eugene Kenny

  • Calling each_pair or each_value on an ActionController::Parameters
    without passing a block now returns an enumerator.

    Eugene Kenny

  • fixture_file_upload now uses path relative to file_fixture_path

    Previously the path had to be relative to fixture_path.
    You can change your existing code as follow:

    # Before
    fixture_file_upload('files/dog.png')
    
    # After
    fixture_file_upload('dog.png')
    

    Edouard Chin

  • Remove deprecated force_ssl at the controller level.

    Rafael Mendonça França

  • The +helper+ class method for controllers loads helper modules specified as
    strings/symbols with String#constantize instead of require_dependency.

    Remember that support for strings/symbols is only a convenient API. You can
    always pass a module object:

    helper UtilsHelper
    

    which is recommended because it is simple and direct. When a string/symbol
    is received, helper just manipulates and inflects the argument to obtain
    that same module object.

    Xavier Noria, Jean Boussier

  • Correctly identify the entire localhost IPv4 range as trusted proxy.

    Nick Soracco

  • url_for will now use "https://" as the default protocol when
    Rails.application.config.force_ssl is set to true.

    Jonathan Hefner

  • Accept and default to base64_urlsafe CSRF tokens.

    Base64 strict-encoded CSRF tokens are not inherently websafe, which makes
    them difficult to deal with. For example, the common practice of sending
    the CSRF token to a browser in a client-readable cookie does not work properly
    out of the box: the value has to be url-encoded and decoded to survive transport.

    Now, we generate Base64 urlsafe-encoded CSRF tokens, which are inherently safe
    to transport. Validation accepts both urlsafe tokens, and strict-encoded tokens
    for backwards compatibility.

    Scott Blum

  • Support rolling deploys for cookie serialization/encryption changes.

    In a distributed configuration like rolling update, users may observe
    both old and new instances during deployment. Users may be served by a
    new instance and then by an old instance.

    That means when the server changes cookies_serializer from :marshal
    to :hybrid or the server changes use_authenticated_cookie_encryption
    from false to true, users may lose their sessions if they access the
    server during deployment.

    We added fallbacks to downgrade the cookie format when necessary during
    deployment, ensuring compatibility on both old and new instances.

    Masaki Hara

  • ActionDispatch::Request.remote_ip has ip address even when all sites are trusted.

    Before, if all X-Forwarded-For sites were trusted, the remote_ip would default to 127.0.0.1.
    Now, the furthest proxy site is used. e.g.: It now gives an ip address when using curl from the load balancer.

    Keenan Brock

  • Fix possible information leak / session hijacking vulnerability.

    The ActionDispatch::Session::MemcacheStore is still vulnerable given it requires the
    gem dalli to be updated as well.

    CVE-2019-16782.

  • Include child session assertion count in ActionDispatch::IntegrationTest.

    IntegrationTest#open_session uses dup to create the new session, which
    meant it had its own copy of @assertions. This prevented the assertions
    from being correctly counted and reported.

    Child sessions now have their attr_accessor overridden to delegate to the
    root session.

    Fixes #32142.

    Sam Bostock

  • Add SameSite protection to every written cookie.

    Enabling SameSite cookie protection is an addition to CSRF protection,
    where cookies won't be sent by browsers in cross-site POST requests when set to :lax.

    :strict disables cookies being sent in cross-site GET or POST requests.

    Passing :none disables this protection and is the same as previous versions albeit a ; SameSite=None is appended to the cookie.

    See upgrade instructions in config/initializers/new_framework_defaults_6_1.rb.

    More info here

    NB: Technically already possible as Rack supports SameSite protection, this is to ensure it's applied to all cookies

    Cédric Fabianski

  • Bring back the feature that allows loading external route files from the router.

    This feature existed back in 2012 but got reverted with the incentive that
    https://github.com/rails/routing_concerns was a better approach. Turned out
    that this wasn't fully the case and loading external route files from the router
    can be helpful for applications with a really large set of routes.
    Without this feature, application needs to implement routes reloading
    themselves and it's not straightforward.

    # config/routes.rb
    
    Rails.application.routes.draw do
      draw(:admin)
    end
    
    # config/routes/admin.rb
    
    get :foo, to: 'foo#bar'
    

    Yehuda Katz, Edouard Chin

  • Fix system test driver option initialization for non-headless browsers.

    glaszig

  • redirect_to.action_controller notifications now include the ActionDispatch::Request in
    their payloads as :request.

    Austin Story

  • respond_to#any no longer returns a response's Content-Type based on the
    request format but based on the block given.

    Example:

      def my_action
        respond_to do |format|
          format.any { render(json: { foo: 'bar' }) }
        end
      end
    
      get('my_action.csv')
    

    The previous behaviour was to respond with a text/csv Content-Type which
    is inaccurate since a JSON response is being rendered.

    Now it correctly returns a application/json Content-Type.

    Edouard Chin

  • Replaces (back)slashes in failure screenshot image paths with dashes.

    If a failed test case contained a slash or a backslash, a screenshot would be created in a
    nested directory, causing issues with tmp:clear.

    Damir Zekic

  • Add params.member? to mimic Hash behavior.

    Younes Serraj

  • process_action.action_controller notifications now include the following in their payloads:

    • :request - the ActionDispatch::Request
    • :response - the ActionDispatch::Response

    George Claghorn

  • Updated ActionDispatch::Request.remote_ip setter to clear set the instance
    remote_ip to nil before setting the header that the value is derived
    from.

    Fixes #37383.

    Norm Provost

  • ActionController::Base.log_at allows setting a different log level per request.

    # Use the debug level if a particular cookie is set.
    class ApplicationController < ActionController::Base
      log_at :debug, if: -> { cookies[:debug] }
    end
    

    George Claghorn

  • Allow system test screen shots to be taken more than once in
    a test by prefixing the file name with an incrementing counter.

    Add an environment variable RAILS_SYSTEM_TESTING_SCREENSHOT_HTML to
    enable saving of HTML during a screenshot in addition to the image.
    This uses the same image name, with the extension replaced with .html

    Tom Fakes

  • Add Vary: Accept header when using Accept header for response.

    For some requests like /users/1, Rails uses requests' Accept
    header to determine what to return. And if we don't add Vary
    in the response header, browsers might accidentally cache different
    types of content, which would cause issues: e.g. javascript got displayed
    instead of html content. This PR fixes these issues by adding Vary: Accept
    in these types of requests. For more detailed problem description, please read:

    https://github.com/rails/rails/pull/36213

    Fixes #25842.

    Stan Lo

  • Fix IntegrationTest follow_redirect! to follow redirection using the same HTTP verb when following
    a 307 redirection.

    Edouard Chin

  • System tests require Capybara 3.26 or newer.

    George Claghorn

  • Reduced log noise handling ActionController::RoutingErrors.

    Alberto Fernández-Capel

  • Add DSL for configuring HTTP Feature Policy.

    This new DSL provides a way to configure an HTTP Feature Policy at a
    global or per-controller level. Full details of HTTP Feature Policy
    specification and guidelines can be found at MDN:

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy

    Example global policy:

    Rails.application.config.feature_policy do |f|
      f.camera      :none
      f.gyroscope   :none
      f.microphone  :none
      f.usb         :none
      f.fullscreen  :self
      f.payment     :self, "https://secure.example.com"
    end
    

    Example controller level policy:

    class PagesController < ApplicationController
      feature_policy do |p|
        p.geolocation "https://example.com"
      end
    end
    

    Jacob Bednarz

  • Add the ability to set the CSP nonce only to the specified directives.

    Fixes #35137.

    Yuji Yaginuma

  • Keep part when scope option has value.

    When a route was defined within an optional scope, if that route didn't
    take parameters the scope was lost when using path helpers. This commit
    ensures scope is kept both when the route takes parameters or when it
    doesn't.

    Fixes #33219.

    Alberto Almagro

  • Added deep_transform_keys and deep_transform_keys! methods to ActionController::Parameters.

    Gustavo Gutierrez

  • Calling ActionController::Parameters#transform_keys/! without a block now returns
    an enumerator for the parameters instead of the underlying hash.

    Eugene Kenny

  • Fix strong parameters blocks all attributes even when only some keys are invalid (non-numerical).
    It should only block invalid key's values instead.

    Stan Lo

Active Job

  • Recover nano precision when serializing Time, TimeWithZone and DateTime objects.

    Alan Tan

  • Deprecate config.active_job.return_false_on_aborted_enqueue.

    Rafael Mendonça França

  • Return false when enqueuing a job is aborted.

    Rafael Mendonça França

  • While using perform_enqueued_jobs test helper enqueued jobs must be stored for the later check with
    assert_enqueued_with.

    Dmitry Polushkin

  • ActiveJob::TestCase#perform_enqueued_jobs without a block removes performed jobs from the queue.

    That way the helper can be called multiple times and not perform a job invocation multiple times.

    def test_jobs
      HelloJob.perform_later("rafael")
      perform_enqueued_jobs # only runs with "rafael"
      HelloJob.perform_later("david")
      perform_enqueued_jobs # only runs with "david"
    end
    

    Étienne Barrié

  • ActiveJob::TestCase#perform_enqueued_jobs will no longer perform retries:

    When calling perform_enqueued_jobs without a block, the adapter will
    now perform jobs that are already in the queue. Jobs that will end up in
    the queue afterwards won't be performed.

    This change only affects perform_enqueued_jobs when no block is given.

    Edouard Chin

  • Add queue name support to Que adapter.

    Brad Nauta, Wojciech Wnętrzak

  • Don't run after_enqueue and after_perform callbacks if the callback chain is halted.

    class MyJob < ApplicationJob
      before_enqueue { throw(:abort) }
      after_enqueue { # won't enter here anymore }
    end
    

    after_enqueue and after_perform callbacks will no longer run if the callback chain is halted.
    This behaviour is a breaking change and won't take effect until Rails 6.2.
    To enable this behaviour in your app right now, you can add in your app's configuration file
    config.active_job.skip_after_callbacks_if_terminated = true.

    Edouard Chin

  • Fix enqueuing and performing incorrect logging message.

    Jobs will no longer always log "Enqueued MyJob" or "Performed MyJob" when they actually didn't get enqueued/performed.

      class MyJob < ApplicationJob
        before_enqueue { throw(:abort) }
      end
    
      MyJob.perform_later # Will no longer log "Enqueued MyJob" since job wasn't even enqueued through adapter.
    

    A new message will be logged in case a job couldn't be enqueued, either because the callback chain was halted or
    because an exception happened during enqueing. (i.e. Redis is down when you try to enqueue your job)

    Edouard Chin

  • Add an option to disable logging of the job arguments when enqueuing and executing the job.

    class SensitiveJob < ApplicationJob
      self.log_arguments = false
    
      def perform(my_sensitive_argument)
      end
    end
    

    When dealing with sensitive arguments as password and tokens it is now possible to configure the job
    to not put the sensitive argument in the logs.

    Rafael Mendonça França

  • Changes in queue_name_prefix of a job no longer affects all other jobs.

    Fixes #37084.

    Lucas Mansur

  • Allow Class and Module instances to be serialized.

    Kevin Deisz

  • Log potential matches in assert_enqueued_with and assert_performed_with.

    Gareth du Plooy

  • Add at argument to the perform_enqueued_jobs test helper.

    John Crepezzi, Eileen Uchitelle

  • assert_enqueued_with and assert_performed_with can now test jobs with relative delay.

    Vlado Cingel

  • Add jitter to ActiveJob::Exceptions.retry_on.

    ActiveJob::Exceptions.retry_on now uses a random amount of jitter in order to
    prevent the thundering herd effect. Defaults to
    15% (represented as 0.15) but overridable via the :jitter option when using retry_on.
    Jitter is applied when an Integer, ActiveSupport::Duration or :exponentially_longer, is passed to the wait argument in retry_on.

    retry_on(MyError, wait: :exponentially_longer, jitter: 0.30)
    

    Anthony Ross

Action Mailer

  • Remove deprecated ActionMailer::Base.receive in favor of Action Mailbox.

    Rafael Mendonça França

  • Fix ActionMailer assertions don't work for parameterized mail with legacy delivery job.

    bogdanvlviv

  • Added email_address_with_name to properly escape addresses with names.

    Sunny Ripert

Action Cable

  • ActionCable::Connection::Base now allows intercepting unhandled exceptions
    with rescue_from before they are logged, which is useful for error reporting
    tools and other integrations.

    Justin Talbott

  • Add ActionCable::Channel#stream_or_reject_for to stream if record is present, otherwise reject the connection

    Atul Bhosale

  • Add ActionCable::Channel#stop_stream_from and #stop_stream_for to unsubscribe from a specific stream.

    Zhang Kang

  • Add PostgreSQL subscription connection identificator.

    Now you can distinguish Action Cable PostgreSQL subscription connections among others.
    Also, you can set custom id in cable.yml configuration.

    SELECT application_name FROM pg_stat_activity;
    /*
        application_name
    ------------------------
    psql
    ActionCable-PID-42
    (2 rows)
    */
    

    Sergey Ponomarev

  • Subscription confirmations and rejections are now logged at the DEBUG level instead of INFO.

    DHH

Active Storage

  • Remove deprecated support to pass :combine_options operations to ActiveStorage::Transformers::ImageProcessing.

    Rafael Mendonça França

  • Remove deprecated ActiveStorage::Transformers::MiniMagickTransformer.

    Rafael Mendonça França

  • Remove deprecated config.active_storage.queue.

    Rafael Mendonça França

  • Remove deprecated ActiveStorage::Downloading.

    Rafael Mendonça França

  • Add per-environment configuration support

    Pietro Moro

  • The Poppler PDF previewer renders a preview image using the original
    document's crop box rather than its media box, hiding print margins. This
    matches the behavior of the MuPDF previewer.

    Vincent Robert

  • Touch parent model when an attachment is purged.

    Víctor Pérez Rodríguez

  • Files can now be served by proxying them from the underlying storage service
    instead of redirecting to a signed service URL. Use the
    rails_storage_proxy_path and _url helpers to proxy an attached file:

    <%= image_tag rails_storage_proxy_path(@user.avatar) %>
    

    To proxy by default, set config.active_storage.resolve_model_to_route:

    # Proxy attached files instead.
    config.active_storage.resolve_model_to_route = :rails_storage_proxy
    
    <%= image_tag @user.avatar %>
    

    To redirect to a signed service URL when the default file serving strategy
    is set to proxying, use the rails_storage_redirect_path and _url helpers:

    <%= image_tag rails_storage_redirect_path(@user.avatar) %>
    

    Jonathan Fleckenstein

  • Add config.active_storage.web_image_content_types to allow applications
    to add content types (like image/webp) in which variants can be processed,
    instead of letting those images be converted to the fallback PNG format.

    Jeroen van Haperen

  • Add support for creating variants of WebP images out of the box.

    Dino Maric

  • Only enqueue analysis jobs for blobs with non-null analyzer classes.

    Gannon McGibbon

  • Previews are created on the same service as the original blob.

    Peter Zhu

  • Remove unused disposition and content_type query parameters for DiskService.

    Peter Zhu

  • Use DiskController for both public and private files.

    DiskController is able to handle multiple services by adding a
    service_name field in the generated URL in DiskService.

    Peter Zhu

  • Variants are tracked in the database to avoid existence checks in the storage service.

    George Claghorn

  • Deprecate service_url methods in favour of url.

    Deprecate Variant#service_url and Preview#service_url to instead use
    #url method to be consistent with Blob.

    Peter Zhu

  • Permanent URLs for public storage blobs.

    Services can be configured in config/storage.yml with a new key
    public: true | false to indicate whether a service holds public
    blobs or private blobs. Public services will always return a permanent URL.

    Deprecates Blob#service_url in favor of Blob#url.

    Peter Zhu

  • Make services aware of configuration names.

    Gannon McGibbon

  • The Content-Type header is set on image variants when they're uploaded to third-party storage services.

    Kyle Ribordy

  • Allow storage services to be configured per attachment.

    class User < ActiveRecord::Base
      has_one_attached :avatar, service: :s3
    end
    
    class Gallery < ActiveRecord::Base
      has_many_attached :photos, service: :s3
    end
    

    Dmitry Tsepelev

  • You can optionally provide a custom blob key when attaching a new file:

    user.avatar.attach key: "avatars/#{user.id}.jpg",
      io: io, content_type: "image/jpeg", filename: "avatar.jpg"
    

    Active Storage will store the blob's data on the configured service at the provided key.

    George Claghorn

  • Replace Blob.create_after_upload! with Blob.create_and_upload! and deprecate the former.

    create_after_upload! has been removed since it could lead to data
    corruption by uploading to a key on the storage service which happened to
    be already taken. Creating the record would then correctly raise a
    database uniqueness exception but the stored object would already have
    overwritten another. create_and_upload! swaps the order of operations
    so that the key gets reserved up-front or the uniqueness error gets raised,
    before the upload to a key takes place.

    Julik Tarkhanov

  • Set content disposition in direct upload using filename and disposition parameters to ActiveStorage::Service#headers_for_direct_upload.

    Peter Zhu

  • Allow record to be optionally passed to blob finders to make sharding
    easier.

    Gannon McGibbon

  • Switch from azure-storage gem to azure-storage-blob gem for Azure service.

    Peter Zhu

  • Add config.active_storage.draw_routes to disable Active Storage routes.

    Gannon McGibbon

  • Image analysis is skipped if ImageMagick returns an error.

    ActiveStorage::Analyzer::ImageAnalyzer#metadata would previously raise a
    MiniMagick::Error, which caused persistent ActiveStorage::AnalyzeJob
    failures. It now logs the error and returns {}, resulting in no metadata
    being added to the offending image blob.

    George Claghorn

  • Method calls on singular attachments return nil when no file is attached.

    Previously, assuming the following User model, user.avatar.filename would
    raise a Module::DelegationError if no avatar was attached:

    class User < ApplicationRecord
      has_one_attached :avatar
    end
    

    They now return nil.

    Matthew Tanous

  • The mirror service supports direct uploads.

    New files are directly uploaded to the primary service. When a
    directly-uploaded file is attached to a record, a background job is enqueued
    to copy it to each secondary service.

    Configure the queue used to process mirroring jobs by setting
    config.active_storage.queues.mirror. The default is :active_storage_mirror.

    George Claghorn

  • The S3 service now permits uploading files larger than 5 gigabytes.

    When uploading a file greater than 100 megabytes in size, the service
    transparently switches to multipart uploads
    using a part size computed from the file's total size and S3's part count limit.

    No application changes are necessary to take advantage of this feature. You
    can customize the default 100 MB multipart upload threshold in your S3
    service's configuration:

    production:
      service: s3
      access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
      secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
      region: us-east-1
      bucket: my-bucket
      upload:
        multipart_threshold: <%= 250.megabytes %>
    

    George Claghorn

Action Mailbox

  • Sendgrid ingress now passes through the envelope recipient as X-Original-To.

    Mark Haussmann

  • Update Mandrill inbound email route to respond appropriately to HEAD requests for URL health checks from Mandrill.

    Bill Cromie

  • Add way to deliver emails via source instead of filling out a form through the conductor interface.

    DHH

  • Mailgun ingress now passes through the envelope recipient as X-Original-To.

    Rikki Pitt

  • Deprecate Rails.application.credentials.action_mailbox.api_key and MAILGUN_INGRESS_API_KEY in favor of Rails.application.credentials.action_mailbox.signing_key and MAILGUN_INGRESS_SIGNING_KEY.

    Matthijs Vos

  • Allow easier creation of multi-part emails from the create_inbound_email_from_mail and receive_inbound_email_from_mail test helpers.

    Michael Herold

  • Fix Bcc header not being included with emails from create_inbound_email_from test helpers.

    jduff

  • Add ApplicationMailbox.mailbox_for to expose mailbox routing.

    James Dabbs

Action Text

  • Declare ActionText::FixtureSet.attachment to generate an
    <action-text-attachment sgid="..."></action-text-attachment> element with
    a valid sgid attribute.

    hello_world_review_content:
      record: hello_world (Review)
      name: content
      body: <p><%= ActionText::FixtureSet.attachment("messages", :hello_world) %> is great!</p>
    

    Sean Doyle

  • Locate fill_in_rich_text_area by <label> text

    In addition to searching for <trix-editor> elements with the appropriate
    aria-label attribute, also support locating elements that match the
    corresponding <label> element's text.

    Sean Doyle

  • Be able to add a default value to rich_text_area.

    form.rich_text_area :content, value: "<h1>Hello world</h1>"
    #=> <input type="hidden" name="message[content]" id="message_content_trix_input_message_1" value="<h1>Hello world</h1>">
    

    Paulo Ancheta

  • Add method to confirm rich text content existence by adding ? after rich
    text attribute.

    message = Message.create!(body: "<h1>Funny times!</h1>")
    message.body? #=> true
    

    Kyohei Toyoda

  • The fill_in_rich_text_area system test helper locates a Trix editor
    and fills it in with the given HTML.

    # <trix-editor id="message_content" ...></trix-editor>
    fill_in_rich_text_area "message_content", with: "Hello <em>world!</em>"
    
    # <trix-editor placeholder="Your message here" ...></trix-editor>
    fill_in_rich_text_area "Your message here", with: "Hello <em>world!</em>"
    
    # <trix-editor aria-label="Message content" ...></trix-editor>
    fill_in_rich_text_area "Message content", with: "Hello <em>world!</em>"
    
    # <input id="trix_input_1" name="message[content]" type="hidden">
    # <trix-editor input="trix_input_1"></trix-editor>
    fill_in_rich_text_area "message[content]", with: "Hello <em>world!</em>"
    

    George Claghorn

Railties

  • Added Railtie#server hook called when Rails starts a server.
    This is useful in case your application or a library needs to run
    another process next to the Rails server. This is quite common in development
    for instance to run the Webpack or the React server.

    It can be used like this:

      class MyRailtie < Rails::Railtie
        server do
          WebpackServer.run
        end
      end
    

    Edouard Chin

  • Remove deprecated rake dev:cache tasks.

    Rafael Mendonça França

  • Remove deprecated rake routes tasks.

    Rafael Mendonça França

  • Remove deprecated rake initializers tasks.

    Rafael Mendonça França

  • Remove deprecated support for using the HOST environment variable to specify the server IP.

    Rafael Mendonça França

  • Remove deprecated server argument from the rails server command.

    Rafael Mendonça França

  • Remove deprecated SOURCE_ANNOTATION_DIRECTORIES environment variable support from rails notes.

    Rafael Mendonça França

  • Remove deprecated connection option in the rails dbconsole command.

    Rafael Mendonça França

  • Remove depreated rake notes tasks.

    Rafael Mendonça França

  • Return a 405 Method Not Allowed response when a request uses an unknown HTTP method.

    Fixes #38998.

    Loren Norman

  • Make railsrc file location xdg-specification compliant

    rails new will now look for the default railsrc file at
    $XDG_CONFIG_HOME/rails/railsrc (or ~/.config/rails/railsrc if
    XDG_CONFIG_HOME is not set). If this file does not exist, rails new
    will fall back to ~/.railsrc.

    The fallback behaviour means this does not cause any breaking changes.

    Nick Wolf

  • Change the default logging level from :debug to :info to avoid inadvertent exposure of personally
    identifiable information (PII) in production environments.

    Eric M. Payne

  • Automatically generate abstract class when using multiple databases.

    When generating a scaffold for a multiple database application, Rails will now automatically generate the abstract class for the database when the database argument is passed. This abstract class will include the connection information for the writing configuration and any models generated for that database will automatically inherit from the abstract class.

    Usage:

    $ bin/rails generate scaffold Pet name:string --database=animals
    

    Will create an abstract class for the animals connection.

    class AnimalsRecord < ApplicationRecord
      self.abstract_class = true
    
      connects_to database: { writing: :animals }
    end
    

    And generate a Pet model that inherits from the new AnimalsRecord:

    class Pet < AnimalsRecord
    end
    

    If you already have an abstract class and it follows a different pattern than Rails defaults, you can pass a parent class with the database argument.

    $ bin/rails generate scaffold Pet name:string --database=animals --parent=SecondaryBase
    

    This will ensure the model inherits from the SecondaryBase parent instead of AnimalsRecord

    class Pet < SecondaryBase
    end
    

    Eileen M. Uchitelle, John Crepezzi

  • Accept params from url to prepopulate the Inbound Emails form in Rails conductor.

    Chris Oliver

  • Create a new rails app using a minimal stack.

    rails new cool_app --minimal

    All the following are excluded from your minimal stack:

    • action_cable
    • action_mailbox
    • action_mailer
    • action_text
    • active_job
    • active_storage
    • bootsnap
    • jbuilder
    • spring
    • system_tests
    • turbolinks
    • webpack

    Haroon Ahmed, DHH

  • Add default ENV variable option with BACKTRACE to turn off backtrace cleaning when debugging framework code in the
    generated config/initializers/backtrace_silencers.rb.

    BACKTRACE=1 ./bin/rails runner "MyClass.perform"

    DHH

  • The autoloading guide for Zeitwerk mode documents how to autoload classes
    during application boot in a safe way.

    Haroon Ahmed, Xavier Noria

  • The classic autoloader starts its deprecation cycle.

    New Rails projects are strongly discouraged from using classic, and we recommend that existing projects running on classic switch to zeitwerk mode when upgrading. Please check the Upgrading Ruby on Rails guide for tips.

    Xavier Noria

  • Adds rails test:all for running all tests in the test directory.

    This runs all test files in the test directory, including system tests.

    Niklas Häusele

  • Add config.generators.after_generate for processing to generated files.

    Register a callback that will get called right after generators has finished.

    Yuji Yaginuma

  • Make test file patterns configurable via Environment variables

    This makes test file patterns configurable via two environment variables:
    DEFAULT_TEST, to configure files to test, and DEFAULT_TEST_EXCLUDE,
    to configure files to exclude from testing.

    These values were hardcoded before, which made it difficult to add
    new categories of tests that should not be executed by default (e.g:
    smoke tests).

    Jorge Manrubia

  • No longer include rake rdoc task when generating plugins.

    To generate docs, use the rdoc lib command instead.

    Jonathan Hefner

  • Allow relative paths with trailing slashes to be passed to rails test.

    Eugene Kenny

  • Add rack-mini-profiler gem to the default Gemfile.

    rack-mini-profiler displays performance information such as SQL time and flame graphs.
    It's enabled by default in development environment, but can be enabled in production as well.
    See the gem README for information on how to enable it in production.

    Osama Sayegh

  • rails stats will now count TypeScript files toward JavaScript stats.

    Joshua Cody

  • Run git init when generating plugins.

    Opt out with --skip-git.

    OKURA Masafumi

  • Add benchmark generator.

    Introduce benchmark generator to benchmark Rails applications.

    rails generate benchmark opt_compare

    This creates a benchmark file that uses benchmark-ips.
    By default, two code blocks can be benchmarked using the before and after reports.

    You can run the generated benchmark file using:
    ruby script/benchmarks/opt_compare.rb

    Kevin Jalbert, Gannon McGibbon

  • Cache compiled view templates when running tests by default.

    When generating a new app without --skip-spring, caching classes is
    disabled in environments/test.rb. This implicitly disables caching
    view templates too. This change will enable view template caching by
    adding this to the generated environments/test.rb:

    config.action_view.cache_template_loading = true
    

    Jorge Manrubia

  • Introduce middleware move operations.

    With this change, you no longer need to delete and reinsert a middleware to
    move it from one place to another in the stack:

    config.middleware.move_before ActionDispatch::Flash, Magical::Unicorns
    

    This will move the Magical::Unicorns middleware before
    ActionDispatch::Flash. You can also move it after with:

    config.middleware.move_after ActionDispatch::Flash, Magical::Unicorns
    

    Genadi Samokovarov

  • Generators that inherit from NamedBase respect --force option.

    Josh Brody

  • Allow configuration of eager_load behaviour for rake environment:

    config.rake_eager_load
    

    Defaults to false as per previous behaviour.

    Thierry Joyal

  • Ensure Rails migration generator respects system-wide primary key config.

    When rails is configured to use a specific primary key type:

    config.generators do |g|
      g.orm :active_record, primary_key_type: :uuid
    end
    

    Previously:

    $ bin/rails g migration add_location_to_users location:references
    

    The references line in the migration would not have type: :uuid.
    This change causes the type to be applied appropriately.

    Louis-Michel Couture, Dermot Haughey

  • Deprecate Rails::DBConsole#config.

    Rails::DBConsole#config is deprecated without replacement. Use Rails::DBConsole.db_config.configuration_hash instead.

    Eileen M. Uchitelle, John Crepezzi

  • Rails.application.config_for merges shared configuration deeply.

    # config/example.yml
    shared:
      foo:
        bar:
          baz: 1
    development:
      foo:
        bar:
          qux: 2
    
    # Previously
    Rails.application.config_for(:example)[:foo][:bar] #=> { qux: 2 }
    
    # Now
    Rails.application.config_for(:example)[:foo][:bar] #=> { baz: 1, qux: 2 }
    

    Yuhei Kiriyama

  • Remove access to values in nested hashes returned by Rails.application.config_for via String keys.

    # config/example.yml
    development:
      options:
        key: value
    
    Rails.application.config_for(:example).options
    

    This used to return a Hash on which you could access values with String keys. This was deprecated in 6.0, and now doesn't work anymore.

    Étienne Barrié

  • Configuration files for environments (config/environments/*.rb) are
    now able to modify autoload_paths, autoload_once_paths, and
    eager_load_paths.

    As a consequence, applications cannot autoload within those files. Before, they technically could, but changes in autoloaded classes or modules had no effect anyway in the configuration because reloading does not reboot.

    Ways to use application code in these files:

    • Define early in the boot process a class that is not reloadable, from which the application takes configuration values that get passed to the framework.

      # In config/application.rb, for example.
      require "#{Rails.root}/lib/my_app/config"
      
      # In config/environments/development.rb, for example.
      config.foo = MyApp::Config.foo
      
    • If the class has to be reloadable, then wrap the configuration code in a to_prepare block:

      config.to_prepare do
        config.foo = MyModel.foo
      end
      

      That assigns the latest MyModel.foo to config.foo when the application boots, and each time there is a reload. But whether that has an effect or not depends on the configuration point, since it is not uncommon for engines to read the application configuration during initialization and set their own state from them. That process happens only on boot, not on reloads, and if that is how config.foo worked, resetting it would have no effect in the state of the engine.

    Allen Hsu & Xavier Noria

  • Support using environment variable to set pidfile.

    Ben Thorner

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 6.0.3.4

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • [CVE-2020-8264] Prevent XSS in Actionable Exceptions

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 5 years ago

https://github.com/rails/rails - 6.0.3.3

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • [CVE-2020-8185] Fix potential XSS vulnerability in the translate/t helper.

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca almost 6 years ago

https://github.com/rails/rails - 5.2.4.4

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • [CVE-2020-15169] Fix potential XSS vulnerability in the translate/t helper

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca almost 6 years ago

https://github.com/rails/rails - 6.0.3.2

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • [CVE-2020-8185] Only allow ActionableErrors if show_detailed_exceptions is enabled

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca almost 6 years ago

https://github.com/rails/rails - 6.0.3.1

Active Support

  • [CVE-2020-8165] Deprecate Marshal.load on raw cache read in RedisCacheStore

  • [CVE-2020-8165] Avoid Marshal.load on raw cache value in MemCacheStore

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • [CVE-2020-8167] Check that request is same-origin prior to including CSRF token in XHRs

Action Pack

  • [CVE-2020-8166] HMAC raw CSRF token before masking it, so it cannot be used to reconstruct a per-form token

  • [CVE-2020-8164] Return self when calling #each, #each_pair, and #each_value instead of the raw @parameters hash

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • [CVE-2020-8162] Include Content-Length in signature for ActiveStorage direct upload

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca about 6 years ago

https://github.com/rails/rails - 4.2.11.3

Action Mailer

  • No changes.

Action Pack

  • No changes.

Action View

  • Backport a missing commit for [CVE-2020-8163]

Active Job

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Active Support

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca about 6 years ago

https://github.com/rails/rails - 4.2.11.2

Action Mailer

  • No changes.

Action Pack

  • No changes.

Action View

  • Restrict local variable names in templates [CVE-2020-8163]

Active Job

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Active Support

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca about 6 years ago

https://github.com/rails/rails - 5.2.4.3

Active Support

  • [CVE-2020-8165] Deprecate Marshal.load on raw cache read in RedisCacheStore

  • [CVE-2020-8165] Avoid Marshal.load on raw cache value in MemCacheStore

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • [CVE-2020-8167] Check that request is same-origin prior to including CSRF token in XHRs

Action Pack

  • [CVE-2020-8166] HMAC raw CSRF token before masking it, so it cannot be used to reconstruct a per-form token

  • [CVE-2020-8164] Return self when calling #each, #each_pair, and #each_value instead of the raw @parameters hash

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • [CVE-2020-8162] Include Content-Length in signature for ActiveStorage direct upload

Railties

  • No changes.

- Ruby
Published by rafaelfranca about 6 years ago

https://github.com/rails/rails - 6.0.3

In this version, we fixed warnings when used with Ruby 2.7 across the entire framework.

Following are the list of other changes, per-framework.

Active Support

  • Array#to_sentence no longer returns a frozen string.

    Before:

    ['one', 'two'].to_sentence.frozen?
    # => true
    

    After:

    ['one', 'two'].to_sentence.frozen?
    # => false
    

    Nicolas Dular

  • Update ActiveSupport::Messages::Metadata#fresh? to work for cookies with expiry set when
    ActiveSupport.parse_json_times = true.

    Christian Gregg

Active Model

  • No changes.

Active Record

  • Recommend applications don't use the database kwarg in connected_to

    The database kwarg in connected_to was meant to be used for one-off scripts but is often used in requests. This is really dangerous because it re-establishes a connection every time. It's deprecated in 6.1 and will be removed in 6.2 without replacement. This change soft deprecates it in 6.0 by removing documentation.

    Eileen M. Uchitelle

  • Fix support for PostgreSQL 11+ partitioned indexes.

    Sebastián Palma

  • Add support for beginless ranges, introduced in Ruby 2.7.

    Josh Goodall

  • Fix insert_all with enum values

    Fixes #38716.

    Joel Blum

  • Regexp-escape table name for MS SQL

    Add Regexp.escape to one method in ActiveRecord, so that table names with regular expression characters in them work as expected. Since MS SQL Server uses "[" and "]" to quote table and column names, and those characters are regular expression characters, methods like pluck and select fail in certain cases when used with the MS SQL Server adapter.

    Larry Reid

  • Store advisory locks on their own named connection.

    Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped.

    In order to fix this we are storing the advisory lock on a new connection with the connection specification name AdisoryLockBase. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this.

    Eileen M. Uchitelle, John Crepezzi

  • Ensure :reading connections always raise if a write is attempted.

    Now Rails will raise an ActiveRecord::ReadOnlyError if any connection on the reading handler attempts to make a write. If your reading role needs to write you should name the role something other than :reading.

    Eileen M. Uchitelle

  • Enforce fresh ETag header after a collection's contents change by adding
    ActiveRecord::Relation#cache_key_with_version. This method will be used by
    ActionController::ConditionalGet to ensure that when collection cache versioning
    is enabled, requests using ConditionalGet don't return the same ETag header
    after a collection is modified. Fixes #38078.

    Aaron Lipman

  • A database URL can now contain a querystring value that contains an equal sign. This is needed to support passing PostgresSQL options.

    Joshua Flanagan

  • Retain explicit selections on the base model after applying includes and joins.

    Resolves #34889.

    Patrick Rebsch

Action View

  • annotated_source_code returns an empty array so TemplateErrors without a
    template in the backtrace are surfaced properly by DebugExceptions.

    Guilherme Mansur, Kasper Timm Hansen

  • Add autoload for SyntaxErrorInTemplate so syntax errors are correctly raised by DebugExceptions.

    Guilherme Mansur, Gannon McGibbon

Action Pack

  • Include child session assertion count in ActionDispatch::IntegrationTest

    IntegrationTest#open_session uses dup to create the new session, which
    meant it had its own copy of @assertions. This prevented the assertions
    from being correctly counted and reported.

    Child sessions now have their attr_accessor overriden to delegate to the
    root session.

    Fixes #32142

    Sam Bostock

Active Job

  • While using perform_enqueued_jobs test helper enqueued jobs must be stored for the later check with
    assert_enqueued_with.

    Dmitry Polushkin

  • Add queue name support to Que adapter

    Brad Nauta, Wojciech Wnętrzak

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • Update Mandrill inbound email route to respond appropriately to HEAD requests for URL health checks from Mandrill.

    Bill Cromie

Action Text

  • No changes.

Railties

  • Cache compiled view templates when running tests by default

    When generating a new app without --skip-spring, caching classes is
    disabled in environments/test.rb. This implicitly disables caching
    view templates too. This change will enable view template caching by
    adding this to the generated environments/test.rb:

    config.action_view.cache_template_loading = true
    

    Jorge Manrubia

  • Rails::Application#eager_load! is available again to load application code
    manually as it was possible in previous versions.

    Please, note this is not integrated with the whole eager loading logic that
    runs when Rails boots with eager loading enabled, you can think of this
    method as a vanilla recursive code loader.

    This ability has been restored because there are some use cases for it, such
    as indexers that need to have all application classes and modules in memory.

    Xavier Noria

  • Generators that inherit from NamedBase respect --force option

    Josh Brody

  • Regression fix: The Rake task zeitwerk:check supports eager loaded
    namespaces which do not have eager load paths, like the recently added
    i18n. These namespaces are only required to respond to eager_load!.

    Xavier Noria

- Ruby
Published by rafaelfranca about 6 years ago

https://github.com/rails/rails - 6.0.3.rc1

Active Support

  • Array#to_sentence no longer returns a frozen string.

    Before:

    ['one', 'two'].to_sentence.frozen?
    # => true
    

    After:

    ['one', 'two'].to_sentence.frozen?
    # => false
    

    Nicolas Dular

  • Update ActiveSupport::Messages::Metadata#fresh? to work for cookies with expiry set when
    ActiveSupport.parse_json_times = true.

    Christian Gregg

Active Model

  • No changes.

Active Record

  • Recommend applications don't use the database kwarg in connected_to

    The database kwarg in connected_to was meant to be used for one-off scripts but is often used in requests. This is really dangerous because it re-establishes a connection every time. It's deprecated in 6.1 and will be removed in 6.2 without replacement. This change soft deprecates it in 6.0 by removing documentation.

    Eileen M. Uchitelle

  • Fix support for PostgreSQL 11+ partitioned indexes.

    Sebastián Palma

  • Add support for beginless ranges, introduced in Ruby 2.7.

    Josh Goodall

  • Fix insert_all with enum values

    Fixes #38716.

    Joel Blum

  • Regexp-escape table name for MS SQL

    Add Regexp.escape to one method in ActiveRecord, so that table names with regular expression characters in them work as expected. Since MS SQL Server uses "[" and "]" to quote table and column names, and those characters are regular expression characters, methods like pluck and select fail in certain cases when used with the MS SQL Server adapter.

    Larry Reid

  • Store advisory locks on their own named connection.

    Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped.

    In order to fix this we are storing the advisory lock on a new connection with the connection specification name AdisoryLockBase. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this.

    Eileen M. Uchitelle, John Crepezzi

  • Ensure :reading connections always raise if a write is attempted.

    Now Rails will raise an ActiveRecord::ReadOnlyError if any connection on the reading handler attempts to make a write. If your reading role needs to write you should name the role something other than :reading.

    Eileen M. Uchitelle

  • Enforce fresh ETag header after a collection's contents change by adding
    ActiveRecord::Relation#cache_key_with_version. This method will be used by
    ActionController::ConditionalGet to ensure that when collection cache versioning
    is enabled, requests using ConditionalGet don't return the same ETag header
    after a collection is modified. Fixes #38078.

    Aaron Lipman

  • A database URL can now contain a querystring value that contains an equal sign. This is needed to support passing PostgresSQL options.

    Joshua Flanagan

  • Retain explicit selections on the base model after applying includes and joins.

    Resolves #34889.

    Patrick Rebsch

Action View

  • annotated_source_code returns an empty array so TemplateErrors without a
    template in the backtrace are surfaced properly by DebugExceptions.

    Guilherme Mansur, Kasper Timm Hansen

  • Add autoload for SyntaxErrorInTemplate so syntax errors are correctly raised by DebugExceptions.

    Guilherme Mansur, Gannon McGibbon

Action Pack

  • Include child session assertion count in ActionDispatch::IntegrationTest

    IntegrationTest#open_session uses dup to create the new session, which
    meant it had its own copy of @assertions. This prevented the assertions
    from being correctly counted and reported.

    Child sessions now have their attr_accessor overriden to delegate to the
    root session.

    Fixes #32142

    Sam Bostock

Active Job

  • While using perform_enqueued_jobs test helper enqueued jobs must be stored for the later check with
    assert_enqueued_with.

    Dmitry Polushkin

  • Add queue name support to Que adapter

    Brad Nauta, Wojciech Wnętrzak

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • Update Mandrill inbound email route to respond appropriately to HEAD requests for URL health checks from Mandrill.

    Bill Cromie

Action Text

  • No changes.

Railties

  • Cache compiled view templates when running tests by default

    When generating a new app without --skip-spring, caching classes is
    disabled in environments/test.rb. This implicitly disables caching
    view templates too. This change will enable view template caching by
    adding this to the generated environments/test.rb:

    config.action_view.cache_template_loading = true
    

    Jorge Manrubia

  • Rails::Application#eager_load! is available again to load application code
    manually as it was possible in previous versions.

    Please, note this is not integrated with the whole eager loading logic that
    runs when Rails boots with eager loading enabled, you can think of this
    method as a vanilla recursive code loader.

    This ability has been restored because there are some use cases for it, such
    as indexers that need to have all application classes and modules in memory.

    Xavier Noria

  • Generators that inherit from NamedBase respect --force option

    Josh Brody

  • Regression fix: The Rake task zeitwerk:check supports eager loaded
    namespaces which do not have eager load paths, like the recently added
    i18n. These namespaces are only required to respond to eager_load!.

    Xavier Noria

- Ruby
Published by rafaelfranca about 6 years ago

https://github.com/rails/rails - 6.0.2.2

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • Fix possible XSS vector in escape_javascript helper

    CVE-2020-5267

    Aaron Patterson

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 6 years ago

https://github.com/rails/rails - 5.2.4.2

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • Fix possible XSS vector in escape_javascript helper

    CVE-2020-5267

    Aaron Patterson

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 6 years ago

https://github.com/rails/rails - 6.0.2.1

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix possible information leak / session hijacking vulnerability.

    The ActionDispatch::Session::MemcacheStore is still vulnerable given it requires the
    gem dalli to be updated as well.

    CVE-2019-16782.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 6 years ago

https://github.com/rails/rails - 5.2.4.1

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • No changes.

Action View

  • No changes.

Action Pack

  • Fix possible information leak / session hijacking vulnerability.

    The ActionDispatch::Session::MemcacheStore is still vulnerable given it requires the
    gem dalli to be updated as well.

    CVE-2019-16782.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 6 years ago

https://github.com/rails/rails - 6.0.2

Active Support

  • Eager load translations during initialization.

    Diego Plentz

  • Use per-thread CPU time clock on ActiveSupport::Notifications.

    George Claghorn

Active Model

  • No changes.

Active Record

  • Share the same connection pool for primary and replica databases in the
    transactional tests for the same database.

    Edouard Chin

  • Fix the preloader when one record is fetched using after_initialize
    but not the entire collection.

    Bradley Price

  • Fix collection callbacks not terminating when :abort is thrown.

    Edouard Chin, Ryuta Kamizono

  • Correctly deprecate where.not working as NOR for relations.

    12a9664 deprecated where.not working as NOR, however
    doing a relation query like where.not(relation: { ... })
    wouldn't be properly deprecated and where.not would work as
    NAND instead.

    Edouard Chin

  • Fix db:migrate task with multiple databases to restore the connection
    to the previous database.

    The migrate task iterates and establish a connection over each db
    resulting in the last one to be used by subsequent rake tasks.
    We should reestablish a connection to the connection that was
    established before the migrate tasks was run

    Edouard Chin

  • Fix multi-threaded issue for AcceptanceValidator.

    Ryuta Kamizono

Action View

  • No changes.

Action Pack

  • Allow using mountable engine route helpers in System Tests.

    Chalo Fernandez

Active Job

Action Mailer

  • Fix ActionMailer assertions don't work for parameterized mail with legacy delivery job.

    bogdanvlviv

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • Fix the collision check for the scaffold generator.

    Ryan Robeson

- Ruby
Published by rafaelfranca over 6 years ago

https://github.com/rails/rails - 6.0.2.rc2

Active Support

  • Eager load translations during initialization.

    Diego Plentz

  • Use per-thread CPU time clock on ActiveSupport::Notifications.

    George Claghorn

Active Model

  • No changes.

Active Record

  • Share the same connection pool for primary and replica databases in the
    transactional tests for the same database.

    Edouard Chin

  • Fix the preloader when one record is fetched using after_initialize
    but not the entire collection.

    Bradley Price

  • Fix collection callbacks not terminating when :abort is thrown.

    Edouard Chin, Ryuta Kamizono

  • Correctly deprecate where.not working as NOR for relations.

    12a9664 deprecated where.not working as NOR, however
    doing a relation query like where.not(relation: { ... })
    wouldn't be properly deprecated and where.not would work as
    NAND instead.

    Edouard Chin

  • Fix db:migrate task with multiple databases to restore the connection
    to the previous database.

    The migrate task iterates and establish a connection over each db
    resulting in the last one to be used by subsequent rake tasks.
    We should reestablish a connection to the connection that was
    established before the migrate tasks was run

    Edouard Chin

  • Fix multi-threaded issue for AcceptanceValidator.

    Ryuta Kamizono

Action View

  • No changes.

Action Pack

  • Allow using mountable engine route helpers in System Tests.

    Chalo Fernandez

Active Job

Action Mailer

  • Fix ActionMailer assertions don't work for parameterized mail with legacy delivery job.

    bogdanvlviv

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • Fix the collision check for the scaffold generator.

    Ryan Robeson

- Ruby
Published by rafaelfranca over 6 years ago

https://github.com/rails/rails - 5.2.4

Active Support

  • Make ActiveSupport::Logger Fiber-safe. Fixes #36752.

    Use Fiber.current.__id__ in ActiveSupport::Logger#local_level= in order
    to make log level local to Ruby Fibers in addition to Threads.

    Example:

    logger = ActiveSupport::Logger.new(STDOUT)
    logger.level = 1
    p "Main is debug? #{logger.debug?}"
    
    Fiber.new {
      logger.local_level = 0
      p "Thread is debug? #{logger.debug?}"
    }.resume
    
    p "Main is debug? #{logger.debug?}"
    

    Before:

    Main is debug? false
    Thread is debug? true
    Main is debug? true
    

    After:

    Main is debug? false
    Thread is debug? true
    Main is debug? false
    

    Alexander Varnin

Active Model

  • Type cast falsy boolean symbols on boolean attribute as false.

    Fixes #35676.

    Ryuta Kamizono

Active Record

  • Fix circular autosave: true causes invalid records to be saved.

    Prior to the fix, when there was a circular series of autosave: true
    associations, the callback for a has_many association was run while
    another instance of the same callback on the same association hadn't
    finished running. When control returned to the first instance of the
    callback, the instance variable had changed, and subsequent associated
    records weren't saved correctly. Specifically, the ID field for the
    belongs_to corresponding to the has_many was nil.

    Fixes #28080.

    Larry Reid

  • PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.

    Fixes #36022.

    Ryuta Kamizono

  • Fix sqlite3 collation parsing when using decimal columns.

    Martin R. Schuster

  • Make ActiveRecord ConnectionPool.connections method thread-safe.

    Fixes #36465.

    Jeff Doering

  • Assign all attributes before calling build to ensure the child record is visible in
    before_add and after_add callbacks for has_many :through associations.

    Fixes #33249.

    Ryan H. Kerr

Action View

  • Allow programmatic click events to trigger Rails UJS click handlers.
    Programmatic click events (eg. ones generated by Rails.fire(link, "click")) don't specify a button. These events were being incorrectly stopped by code meant to ignore scroll wheel and right clicks introduced in #34573.

    Sudara Williams

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • Use original bundler environment variables during the process of generating a new rails project.

    Marco Costa

  • Allow loading seeds without ActiveJob.

    Fixes #35782

    Jeremy Weathers

  • Only force :async ActiveJob adapter to :inline during seeding.

    BatedUrGonnaDie

- Ruby
Published by rafaelfranca over 6 years ago

https://github.com/rails/rails - 6.0.2.rc1

Active Support

  • Eager load translations during initialization.

    Diego Plentz

  • Use per-thread CPU time clock on ActiveSupport::Notifications.

    George Claghorn

Active Model

  • No changes.

Active Record

  • Share the same connection pool for primary and replica databases in the
    transactional tests for the same database.

    Edouard Chin

  • Fix the preloader when one record is fetched using after_initialize
    but not the entire colection.

    Bradley Price

  • Fix collection callbacks not terminating when :abort is thrown.

    Edouard Chin, Ryuta Kamizono

  • Correctly deprecate where.not working as NOR for relations.

    12a9664 deprecated where.not working as NOR, however
    doing a relation query like where.not(relation: { ... })
    wouldn't be properly deprecated and where.not would work as
    NAND instead.

    Edouard Chin

  • Fix db:migrate task with multiple databases to restore the connection
    to the previous database.

    The migrate task iterates and establish a connection over each db
    resulting in the last one to be used by subsequent rake tasks.
    We should reestablish a connection to the connection that was
    established before the migrate tasks was run

    Edouard Chin

  • Fix multi-threaded issue for AcceptanceValidator.

    Ryuta Kamizono

Action View

  • No changes.

Action Pack

  • Allow using mountable engine route helpers in System Tests.

    Chalo Fernandez

Active Job

Action Mailer

  • Fix ActionMailer assertions don't work for parameterized mail with legacy delivery job.

    bogdanvlviv

Action Cable

  • No changes.

Active Storage

  • No changes.

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • Fix the collision check for the scaffold generator.

    Ryan Robeson

  • Configuration files for environments (config/environments/*.rb) are
    now able to modify autoload_paths, autoload_once_paths, and
    eager_load_paths.

    Allen Hsu & Xavier Noria

- Ruby
Published by rafaelfranca over 6 years ago

https://github.com/rails/rails - 5.2.4.rc1

Active Support

  • Make ActiveSupport::Logger Fiber-safe. Fixes #36752.

    Use Fiber.current.__id__ in ActiveSupport::Logger#local_level= in order
    to make log level local to Ruby Fibers in addition to Threads.

    Example:

    logger = ActiveSupport::Logger.new(STDOUT)
    logger.level = 1
    p "Main is debug? #{logger.debug?}"
    
    Fiber.new {
      logger.local_level = 0
      p "Thread is debug? #{logger.debug?}"
    }.resume
    
    p "Main is debug? #{logger.debug?}"
    

    Before:

    Main is debug? false
    Thread is debug? true
    Main is debug? true
    

    After:

    Main is debug? false
    Thread is debug? true
    Main is debug? false
    

    Alexander Varnin

Active Model

  • Type cast falsy boolean symbols on boolean attribute as false.

    Fixes #35676.

    Ryuta Kamizono

Active Record

  • Fix circular autosave: true causes invalid records to be saved.

    Prior to the fix, when there was a circular series of autosave: true
    associations, the callback for a has_many association was run while
    another instance of the same callback on the same association hadn't
    finished running. When control returned to the first instance of the
    callback, the instance variable had changed, and subsequent associated
    records weren't saved correctly. Specifically, the ID field for the
    belongs_to corresponding to the has_many was nil.

    Fixes #28080.

    Larry Reid

  • PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.

    Fixes #36022.

    Ryuta Kamizono

  • Fix sqlite3 collation parsing when using decimal columns.

    Martin R. Schuster

  • Make ActiveRecord ConnectionPool.connections method thread-safe.

    Fixes #36465.

    Jeff Doering

  • Assign all attributes before calling build to ensure the child record is visible in
    before_add and after_add callbacks for has_many :through associations.

    Fixes #33249.

    Ryan H. Kerr

Action View

  • Allow programmatic click events to trigger Rails UJS click handlers.
    Programmatic click events (eg. ones generated by Rails.fire(link, "click")) don't specify a button. These events were being incorrectly stopped by code meant to ignore scroll wheel and right clicks introduced in #34573.

    Sudara Williams

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • Use original bundler environment variables during the process of generating a new rails project.

    Marco Costa

  • Allow loading seeds without ActiveJob.

    Fixes #35782

    Jeremy Weathers

  • Only force :async ActiveJob adapter to :inline during seeding.

    BatedUrGonnaDie

- Ruby
Published by rafaelfranca over 6 years ago

https://github.com/rails/rails - 6.0.1

Active Support

  • ActiveSupport::SafeBuffer supports Enumerator methods.

    Shugo Maeda

  • The Redis cache store fails gracefully when the server returns a "max number of clients reached" error.

    Brandon Medenwald

  • Fixed that mutating a value returned by a memory cache store would unexpectedly change the cached value.

    Jonathan Hyman

  • The default inflectors in zeitwerk mode support overrides:

    # config/initializers/zeitwerk.rb
    Rails.autoloaders.each do |autoloader|
      autoloader.inflector.inflect(
        "html_parser" => "HTMLParser",
        "ssl_error"   => "SSLError"
      )
    end
    

    That way, you can tweak how individual basenames are inflected without touching Active Support inflection rules, which are global. These inflectors fallback to String#camelize, so existing inflection rules are still taken into account for non-overridden basenames.

    Please, check the autoloading guide for zeitwerk mode if you prefer not to depend on String#camelize at all.

    Xavier Noria

  • Improve Range#===, Range#include?, and Range#cover? to work with beginless (startless) and endless range targets.

    Allen Hsu, Andrew Hodgkinson

  • Don't use Process#clock_gettime(CLOCK_PROCESS_CPUTIME_ID) on Solaris

    Iain Beeston

Active Model

  • No changes.

Active Record

  • Common Table Expressions are allowed on read-only connections.

    Chris Morris

  • New record instantiation respects unscope.

    Ryuta Kamizono

  • Fixed a case where find_in_batches could halt too early.

    Takayuki Nakata

  • Autosaved associations always perform validations when a custom validation context is used.

    Tekin Suleyman

  • sql.active_record notifications now include the :connection in their payloads.

    Eugene Kenny

  • A rollback encountered in an after_commit callback does not reset previously-committed record state.

    Ryuta Kamizono

  • Fixed that join order was lost when eager-loading.

    Ryuta Kamizono

  • DESCRIBE queries are allowed on read-only connections.

    Dylan Thacker-Smith

  • Fixed that records that had been inspected could not be marshaled.

    Eugene Kenny

  • The connection pool reaper thread is respawned in forked processes. This fixes that idle connections in forked processes wouldn't be reaped.

    John Hawthorn

  • The memoized result of ActiveRecord::Relation#take is properly cleared when ActiveRecord::Relation#reset or ActiveRecord::Relation#reload is called.

    Anmol Arora

  • Fixed the performance regression for primary_keys introduced MySQL 8.0.

    Hiroyuki Ishii

  • insert, insert_all, upsert, and upsert_all now clear the query cache.

    Eugene Kenny

  • Call while_preventing_writes directly from connected_to.

    In some cases application authors want to use the database switching middleware and make explicit calls with connected_to. It's possible for an app to turn off writes and not turn them back on by the time we call connected_to(role: :writing).

    This change allows apps to fix this by assuming if a role is writing we want to allow writes, except in the case it's explicitly turned off.

    Eileen M. Uchitelle

  • Improve detection of ActiveRecord::StatementTimeout with mysql2 adapter in the edge case when the query is terminated during filesort.

    Kir Shatrov

Action View

  • UJS avoids Element.closest() for IE 9 compatibility.

    George Claghorn

Action Pack

  • ActionDispatch::SystemTestCase now inherits from ActiveSupport::TestCase rather than ActionDispatch::IntegrationTest. This permits running jobs in system tests.

    George Claghorn, Edouard Chin

  • Registered MIME types may contain extra flags:

    Mime::Type.register "text/html; fragment", :html_fragment
    

    Aaron Patterson

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • ActiveStorage::AnalyzeJobs are discarded on ActiveRecord::RecordNotFound errors.

    George Claghorn

  • Blobs are recorded in the database before being uploaded to the service. This fixes that generated blob keys could silently collide, leading to data loss.

    Julik Tarkhanov

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • The zeitwerk:check Rake task reports files outside the app's root directory, as in engines loaded from gems.

    Xavier Noria

  • Fixed a possible error when using the evented file update checker.

    Yuji Yaginuma

  • The sqlite3 database files created by the parallel testing feature are included in the default .gitignore file for newly-generated apps.

    Yasuo Honda

  • rails new generates a .keep file in tmp/pids. This fixes starting a server via rackup instead of rails server.

    Rafael Mendonça França

- Ruby
Published by georgeclaghorn over 6 years ago

https://github.com/rails/rails - 6.0.1.rc1

Active Support

  • ActiveSupport::SafeBuffer supports Enumerator methods.

    Shugo Maeda

  • The Redis cache store fails gracefully when the server returns a "max number
    of clients reached" error.

    Brandon Medenwald

  • Fixed that mutating a value returned by a memory cache store would
    unexpectedly change the cached value.

    Jonathan Hyman

  • The default inflectors in zeitwerk mode support overrides:

    # config/initializers/zeitwerk.rb
    Rails.autoloaders.each do |autoloader|
      autoloader.inflector.inflect(
        "html_parser" => "HTMLParser",
        "ssl_error"   => "SSLError"
      )
    end
    

    That way, you can tweak how individual basenames are inflected without touching Active Support inflection rules, which are global. These inflectors fallback to String#camelize, so existing inflection rules are still taken into account for non-overridden basenames.

    Please, check the autoloading guide for zeitwerk mode if you prefer not to depend on String#camelize at all.

    Xavier Noria

  • Improve Range#===, Range#include?, and Range#cover? to work with beginless (startless)
    and endless range targets.

    Allen Hsu, Andrew Hodgkinson

  • Don't use Process#clock_gettime(CLOCK_PROCESS_CPUTIME_ID) on Solaris

    Iain Beeston

Active Model

  • No changes.

Active Record

  • Common Table Expressions are allowed on read-only connections.

    Chris Morris

  • New record instantiation respects unscope.

    Ryuta Kamizono

  • Fixed a case where find_in_batches could halt too early.

    Takayuki Nakata

  • Autosaved associations always perform validations when a custom validation
    context is used.

    Tekin Suleyman

  • sql.active_record notifications now include the :connection in
    their payloads.

    Eugene Kenny

  • A rollback encountered in an after_commit callback does not reset
    previously-committed record state.

    Ryuta Kamizono

  • Fixed that join order was lost when eager-loading.

    Ryuta Kamizono

  • DESCRIBE queries are allowed on read-only connections.

    Dylan Thacker-Smith

  • Fixed that records that had been inspected could not be marshaled.

    Eugene Kenny

  • The connection pool reaper thread is respawned in forked processes. This
    fixes that idle connections in forked processes wouldn't be reaped.

    John Hawthorn

  • The memoized result of ActiveRecord::Relation#take is properly cleared
    when ActiveRecord::Relation#reset or ActiveRecord::Relation#reload
    is called.

    Anmol Arora

  • Fixed the performance regression for primary_keys introduced MySQL 8.0.

    Hiroyuki Ishii

  • insert, insert_all, upsert, and upsert_all now clear the query cache.

    Eugene Kenny

  • Call while_preventing_writes directly from connected_to.

    In some cases application authors want to use the database switching middleware and make explicit calls with connected_to. It's possible for an app to turn off writes and not turn them back on by the time we call connected_to(role: :writing).

    This change allows apps to fix this by assuming if a role is writing we want to allow writes, except in the case it's explicitly turned off.

    Eileen M. Uchitelle

  • Improve detection of ActiveRecord::StatementTimeout with mysql2 adapter in the edge case when the query is terminated during filesort.

    Kir Shatrov

Action View

  • UJS avoids Element.closest() for IE 9 compatibility.

    George Claghorn

Action Pack

  • ActionDispatch::SystemTestCase now inherits from ActiveSupport::TestCase
    rather than ActionDispatch::IntegrationTest. This permits running jobs in
    system tests.

    George Claghorn, Edouard Chin

  • Registered MIME types may contain extra flags:

    Mime::Type.register "text/html; fragment", :html_fragment
    

    Aaron Patterson

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • ActiveStorage::AnalyzeJobs are discarded on ActiveRecord::RecordNotFound errors.

    George Claghorn

  • Blobs are recorded in the database before being uploaded to the service.
    This fixes that generated blob keys could silently collide, leading to
    data loss.

    Julik Tarkhanov

Action Mailbox

  • No changes.

Action Text

  • No changes.

Railties

  • The zeitwerk:check Rake task reports files outside the app's root
    directory, as in engines loaded from gems.

    Xavier Noria

  • Fixed a possible error when using the evented file update checker.

    Yuji Yaginuma

  • The sqlite3 database files created by the parallel testing feature are
    included in the default .gitignore file for newly-generated apps.

    Yasuo Honda

  • rails new generates a .keep file in tmp/pids. This fixes starting
    a server via rackup instead of rails server.

    Rafael Mendonça França

- Ruby
Published by georgeclaghorn over 6 years ago

https://github.com/rails/rails - 5.2.3

Active Support

  • Add ActiveSupport::HashWithIndifferentAccess#assoc.

    assoc can now be called with either a string or a symbol.

    Stefan Schüßler

  • Fix String#safe_constantize throwing a LoadError for incorrectly cased constant references.

    Keenan Brock

  • Allow Range#=== and Range#cover? on Range

    Range#cover? can now accept a range argument like Range#include? and
    Range#===. Range#=== works correctly on Ruby 2.6. Range#include? is moved
    into a new file, with these two methods.

    utilum

  • If the same block is included multiple times for a Concern, an exception is no longer raised.

    Mark J. Titorenko, Vlad Bokov

Active Model

  • Fix date value when casting a multiparameter date hash to not convert
    from Gregorian date to Julian date.

    Before:

    Day.new({"day(1i)"=>"1", "day(2i)"=>"1", "day(3i)"=>"1"})
    => #<Day id: nil, day: "0001-01-03", created_at: nil, updated_at: nil>
    

    After:

    Day.new({"day(1i)"=>"1", "day(2i)"=>"1", "day(3i)"=>"1"})
    => #<Day id: nil, day: "0001-01-01", created_at: nil, updated_at: nil>
    

    Fixes #28521.

    Sayan Chakraborty

  • Fix numericality equality validation of BigDecimal and Float
    by casting to BigDecimal on both ends of the validation.

    Gannon McGibbon

Active Record

  • Fix different count calculation when using size with manual select with DISTINCT.

    Fixes #35214.

    Juani Villarejo

  • Fix prepared statements caching to be enabled even when query caching is enabled.

    Ryuta Kamizono

  • Don't allow where with invalid value matches to nil values.

    Fixes #33624.

    Ryuta Kamizono

  • Restore an ability that class level update without giving ids.

    Fixes #34743.

    Ryuta Kamizono

  • Fix join table column quoting with SQLite.

    Gannon McGibbon

  • Ensure that delete_all on collection proxy returns affected count.

    Ryuta Kamizono

  • Reset scope after delete on collection association to clear stale offsets of removed records.

    Gannon McGibbon

Action View

  • Prevent non-primary mouse keys from triggering Rails UJS click handlers.
    Firefox fires click events even if the click was triggered by non-primary mouse keys such as right- or scroll-wheel-clicks.
    For example, right-clicking a link such as the one described below (with an underlying ajax request registered on click) should not cause that request to occur.

    <%= link_to 'Remote', remote_path, class: 'remote', remote: true, data: { type: :json } %>
    

    Fixes #34541

    Wolfgang Hobmaier

Action Pack

  • Allow using combine the Cache Control public and no-cache headers.

    Before this change, even if public was specified for Cache Control header,
    it was excluded when no-cache was included. This fixed to keep public
    header as is.

    Fixes #34780.

    Yuji Yaginuma

  • Allow nil params for ActionController::TestCase.

    Ryo Nakamura

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • Seed database with inline ActiveJob job adapter.

    Gannon McGibbon

  • Fix boolean interaction in scaffold system tests.

    Gannon McGibbon

- Ruby
Published by rafaelfranca over 7 years ago

https://github.com/rails/rails - 5.1.7

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • Fix touch option to behave consistently with Persistence#touch method.

    Ryuta Kamizono

  • Back port Rails 5.2 reverse_order Arel SQL literal fix.

    Matt Jones, Brooke Kuhlmann

  • becomes should clear the mutation tracker which is created in after_initialize.

    Fixes #32867.

    Ryuta Kamizono

Action View

  • Fix issue with button_to's to_form_params

    button_to was throwing exception when invoked with params hash that
    contains symbol and string keys. The reason for the exception was that
    to_form_params was comparing the given symbol and string keys.

    The issue is fixed by turning all keys to strings inside
    to_form_params before comparing them.

    Georgi Georgiev

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 7 years ago

https://github.com/rails/rails - 5.1.7.rc1

Active Support

  • No changes.

Active Model

  • No changes.

Active Record

  • Fix touch option to behave consistently with Persistence#touch method.

    Ryuta Kamizono

  • Back port Rails 5.2 reverse_order Arel SQL literal fix.

    Matt Jones, Brooke Kuhlmann

  • becomes should clear the mutation tracker which is created in after_initialize.

    Fixes #32867.

    Ryuta Kamizono

Action View

  • Fix issue with button_to's to_form_params

    button_to was throwing exception when invoked with params hash that
    contains symbol and string keys. The reason for the exception was that
    to_form_params was comparing the given symbol and string keys.

    The issue is fixed by turning all keys to strings inside
    to_form_params before comparing them.

    Georgi Georgiev

Action Pack

  • No changes.

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Railties

  • No changes.

- Ruby
Published by rafaelfranca over 7 years ago

https://github.com/rails/rails - 5.2.3.rc1

Active Support

  • Add ActiveSupport::HashWithIndifferentAccess#assoc.

    assoc can now be called with either a string or a symbol.

    Stefan Schüßler

  • Fix String#safe_constantize throwing a LoadError for incorrectly cased constant references.

    Keenan Brock

  • Allow Range#=== and Range#cover? on Range

    Range#cover? can now accept a range argument like Range#include? and
    Range#===. Range#=== works correctly on Ruby 2.6. Range#include? is moved
    into a new file, with these two methods.

    utilum

  • If the same block is included multiple times for a Concern, an exception is no longer raised.

    Mark J. Titorenko, Vlad Bokov

Active Model

  • Fix date value when casting a multiparameter date hash to not convert
    from Gregorian date to Julian date.

    Before:

    Day.new({"day(1i)"=>"1", "day(2i)"=>"1", "day(3i)"=>"1"})
    => #<Day id: nil, day: "0001-01-03", created_at: nil, updated_at: nil>
    

    After:

    Day.new({"day(1i)"=>"1", "day(2i)"=>"1", "day(3i)"=>"1"})
    => #<Day id: nil, day: "0001-01-01", created_at: nil, updated_at: nil>
    

    Fixes #28521.

    Sayan Chakraborty

  • Fix numericality equality validation of BigDecimal and Float
    by casting to BigDecimal on both ends of the validation.

    Gannon McGibbon

Active Record

  • Fix different count calculation when using size with manual select with DISTINCT.

    Fixes #35214.

    Juani Villarejo

  • Fix prepared statements caching to be enabled even when query caching is enabled.

    Ryuta Kamizono

  • Don't allow where with invalid value matches to nil values.

    Fixes #33624.

    Ryuta Kamizono

  • Restore an ability that class level update without giving ids.

    Fixes #34743.

    Ryuta Kamizono

  • Fix join table column quoting with SQLite.

    Gannon McGibbon

  • Ensure that delete_all on collection proxy returns affected count.

    Ryuta Kamizono

  • Reset scope after delete on collection association to clear stale offsets of removed records.

    Gannon McGibbon

Action View

  • Prevent non-primary mouse keys from triggering Rails UJS click handlers.
    Firefox fires click events even if the click was triggered by non-primary mouse keys such as right- or scroll-wheel-clicks.
    For example, right-clicking a link such as the one described below (with an underlying ajax request registered on click) should not cause that request to occur.

    <%= link_to 'Remote', remote_path, class: 'remote', remote: true, data: { type: :json } %>
    

    Fixes #34541

    Wolfgang Hobmaier

Action Pack

  • Allow using combine the Cache Control public and no-cache headers.

    Before this change, even if public was specified for Cache Control header,
    it was excluded when no-cache was included. This fixed to keep public
    header as is.

    Fixes #34780.

    Yuji Yaginuma

  • Allow nil params for ActionController::TestCase.

    Ryo Nakamura

Active Job

  • No changes.

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • No changes.

Railties

  • Seed database with inline ActiveJob job adapter.

    Gannon McGibbon

  • Fix boolean interaction in scaffold system tests.

    Gannon McGibbon

- Ruby
Published by rafaelfranca over 7 years ago

https://github.com/rails/rails - 6.0.0.beta1

Active Support

  • Remove deprecated Module#reachable? method.

    Rafael Mendonça França

  • Remove deprecated #acronym_regex method from Inflections.

    Rafael Mendonça França

  • Fix String#safe_constantize throwing a LoadError for incorrectly cased constant references.

    Keenan Brock

  • Preserve key order passed to ActiveSupport::CacheStore#fetch_multi.

    fetch_multi(*names) now returns its results in the same order as the *names requested, rather than returning cache hits followed by cache misses.

    Gannon McGibbon

  • If the same block is included multiple times for a Concern, an exception is no longer raised.

    Mark J. Titorenko, Vlad Bokov

  • Fix bug where #to_options for ActiveSupport::HashWithIndifferentAccess
    would not act as alias for #symbolize_keys.

    Nick Weiland

  • Improve the logic that detects non-autoloaded constants.

    Jan Habermann, Xavier Noria

  • Deprecate ActiveSupport::Multibyte::Unicode#pack_graphemes(array) and ActiveSuppport::Multibyte::Unicode#unpack_graphemes(string)
    in favor of array.flatten.pack("U*") and string.scan(/\X/).map(&:codepoints), respectively.

    Francesco Rodríguez

  • Deprecate ActiveSupport::Multibyte::Chars.consumes? in favor of String#is_utf8?.

    Francesco Rodríguez

  • Fix duration being rounded to a full second.

      time = DateTime.parse("2018-1-1")
      time += 0.51.seconds
    

    Will now correctly add 0.51 second and not 1 full second.

    Edouard Chin

  • Deprecate ActiveSupport::Multibyte::Unicode#normalize and ActiveSuppport::Multibyte::Chars#normalize
    in favor of String#unicode_normalize

    Francesco Rodríguez

  • Deprecate ActiveSupport::Multibyte::Unicode#downcase/upcase/swapcase in favor of
    String#downcase/upcase/swapcase.

    Francesco Rodríguez

  • Add ActiveSupport::ParameterFilter.

    Yoshiyuki Kinjo

  • Rename Module#parent, Module#parents, and Module#parent_name to
    module_parent, module_parents, and module_parent_name.

    Gannon McGibbon

  • Deprecate the use of LoggerSilence in favor of ActiveSupport::LoggerSilence

    Edouard Chin

  • Deprecate using negative limits in String#first and String#last.

    Gannon McGibbon, Eric Turner

  • Fix bug where #without for ActiveSupport::HashWithIndifferentAccess would fail
    with symbol arguments

    Abraham Chan

  • Treat #delete_prefix, #delete_suffix and #unicode_normalize results as non-html_safe.
    Ensure safety of arguments for #insert, #[]= and #replace calls on html_safe Strings.

    Janosch Müller

  • Changed ActiveSupport::TaggedLogging.new to return a new logger instance instead
    of mutating the one received as parameter.

    Thierry Joyal

  • Define unfreeze_time as an alias of travel_back in ActiveSupport::Testing::TimeHelpers.

    The alias is provided for symmetry with freeze_time.

    Ryan Davidson

  • Add support for tracing constant autoloads. Just throw

    ActiveSupport::Dependencies.logger = Rails.logger
    ActiveSupport::Dependencies.verbose = true
    

    in an initializer.

    Xavier Noria

  • Maintain html_safe? on html_safe strings when sliced.

    string = "<div>test</div>".html_safe
    string[-1..1].html_safe? # => true
    

    Elom Gomez, Yumin Wong

  • Add Array#extract!.

    The method removes and returns the elements for which the block returns a true value.
    If no block is given, an Enumerator is returned instead.

    numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9]
    numbers # => [0, 2, 4, 6, 8]
    

    bogdanvlviv

  • Support not to cache nil for ActiveSupport::Cache#fetch.

    cache.fetch('bar', skip_nil: true) { nil }
    cache.exist?('bar') # => false
    

    Martin Hong

  • Add "event object" support to the notification system.
    Before this change, end users were forced to create hand made artisanal
    event objects on their own, like this:

    ActiveSupport::Notifications.subscribe('wait') do |*args|
      @event = ActiveSupport::Notifications::Event.new(*args)
    end
    
    ActiveSupport::Notifications.instrument('wait') do
      sleep 1
    end
    
    @event.duration # => 1000.138
    

    After this change, if the block passed to subscribe only takes one
    parameter, the framework will yield an event object to the block. Now
    end users are no longer required to make their own:

    ActiveSupport::Notifications.subscribe('wait') do |event|
      @event = event
    end
    
    ActiveSupport::Notifications.instrument('wait') do
      sleep 1
    end
    
    p @event.allocations # => 7
    p @event.cpu_time    # => 0.256
    p @event.idle_time   # => 1003.2399
    

    Now you can enjoy event objects without making them yourself. Neat!

    Aaron "t.lo" Patterson

  • Add cpu_time, idle_time, and allocations to Event.

    Eileen M. Uchitelle, Aaron Patterson

  • RedisCacheStore: support key expiry in increment/decrement.

    Pass :expires_in to #increment and #decrement to set a Redis EXPIRE on the key.

    If the key is already set to expire, RedisCacheStore won't extend its expiry.

    Rails.cache.increment("some_key", 1, expires_in: 2.minutes)
    

    Jason Lee

  • Allow Range#=== and Range#cover? on Range.

    Range#cover? can now accept a range argument like Range#include? and
    Range#===. Range#=== works correctly on Ruby 2.6. Range#include? is moved
    into a new file, with these two methods.

    Requiring active_support/core_ext/range/include_range is now deprecated.
    Use require "active_support/core_ext/range/compare_range" instead.

    utilum

  • Add index_with to Enumerable.

    Allows creating a hash from an enumerable with the value from a passed block
    or a default argument.

    %i( title body ).index_with { |attr| post.public_send(attr) }
    # => { title: "hey", body: "what's up?" }
    
    %i( title body ).index_with(nil)
    # => { title: nil, body: nil }
    

    Closely linked with index_by, which creates a hash where the keys are extracted from a block.

    Kasper Timm Hansen

  • Fix bug where ActiveSupport::Timezone.all would fail when tzinfo data for
    any timezone defined in ActiveSupport::TimeZone::MAPPING is missing.

    Dominik Sander

  • Redis cache store: delete_matched no longer blocks the Redis server.
    (Switches from evaled Lua to a batched SCAN + DEL loop.)

    Gleb Mazovetskiy

  • Fix bug where ActiveSupport::Cache will massively inflate the storage
    size when compression is enabled (which is true by default). This patch
    does not attempt to repair existing data: please manually flush the cache
    to clear out the problematic entries.

    Godfrey Chan

  • Fix bug where URI.unescape would fail with mixed Unicode/escaped character input:

    URI.unescape("\xe3\x83\x90")  # => "バ"
    URI.unescape("%E3%83%90")  # => "バ"
    URI.unescape("\xe3\x83\x90%E3%83%90")  # => Encoding::CompatibilityError
    

    Ashe Connor, Aaron Patterson

  • Add before? and after? methods to Date, DateTime,
    Time, and TimeWithZone.

    Nick Holden

  • ActiveSupport::Inflector#ordinal and ActiveSupport::Inflector#ordinalize now support
    translations through I18n.

    # locale/fr.rb
    
    {
      fr: {
        number: {
          nth: {
            ordinals: lambda do |_key, number:, **_options|
              if number.to_i.abs == 1
                'er'
              else
                'e'
              end
            end,
    
            ordinalized: lambda do |_key, number:, **_options|
              "#{number}#{ActiveSupport::Inflector.ordinal(number)}"
            end
          }
        }
      }
    }
    

    Christian Blais

  • Add :private option to ActiveSupport's Module#delegate
    in order to delegate methods as private:

    class User < ActiveRecord::Base
      has_one :profile
      delegate :date_of_birth, to: :profile, private: true
    
      def age
        Date.today.year - date_of_birth.year
      end
    end
    
    # User.new.age  # => 29
    # User.new.date_of_birth
    # => NoMethodError: private method `date_of_birth' called for #<User:0x00000008221340>
    

    Tomas Valent

  • String#truncate_bytes to truncate a string to a maximum bytesize without
    breaking multibyte characters or grapheme clusters like 👩‍👩‍👦‍👦.

    Jeremy Daer

  • String#strip_heredoc preserves frozenness.

    "foo".freeze.strip_heredoc.frozen?  # => true
    

    Fixes that frozen string literals would inadvertently become unfrozen:

    # frozen_string_literal: true
    
    foo = <<-MSG.strip_heredoc
      la la la
    MSG
    
    foo.frozen?  # => false !??
    

    Jeremy Daer

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

  • Adds parallel testing to Rails.

    Parallelize your test suite with forked processes or threads.

    Eileen M. Uchitelle, Aaron Patterson

Active Model

  • Add ActiveModel::Errors#of_kind?.

    bogdanvlviv, Rafael Mendonça França

  • Fix numericality equality validation of BigDecimal and Float
    by casting to BigDecimal on both ends of the validation.

    Gannon McGibbon

  • Add #slice! method to ActiveModel::Errors.

    Daniel López Prat

  • Fix numericality validator to still use value before type cast except Active Record.

    Fixes #33651, #33686.

    Ryuta Kamizono

  • Fix ActiveModel::Serializers::JSON#as_json method for timestamps.

    Before:

    contact = Contact.new(created_at: Time.utc(2006, 8, 1))
    contact.as_json["created_at"] # => 2006-08-01 00:00:00 UTC
    

    After:

    contact = Contact.new(created_at: Time.utc(2006, 8, 1))
    contact.as_json["created_at"] # => "2006-08-01T00:00:00.000Z"
    

    Bogdan Gusiev

  • Allows configurable attribute name for #has_secure_password. This
    still defaults to an attribute named 'password', causing no breaking
    change. There is a new method #authenticate_XXX where XXX is the
    configured attribute name, making the existing #authenticate now an
    alias for this when the attribute is the default 'password'.

    Example:

    class User < ActiveRecord::Base
      has_secure_password :recovery_password, validations: false
    end
    
    user = User.new()
    user.recovery_password = "42password"
    user.recovery_password_digest # => "$2a$04$iOfhwahFymCs5weB3BNH/uX..."
    user.authenticate_recovery_password('42password') # => user
    

    Unathi Chonco

  • Add config.active_model.i18n_full_message in order to control whether
    the full_message error format can be overridden at the attribute or model
    level in the locale files. This is false by default.

    Martin Larochelle

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

Active Record

  • Remove deprecated #set_state from the transaction object.

    Rafael Mendonça França

  • Remove deprecated #supports_statement_cache? from the database adapters.

    Rafael Mendonça França

  • Remove deprecated #insert_fixtures from the database adapters.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::ConnectionAdapters::SQLite3Adapter#valid_alter_table_type?.

    Rafael Mendonça França

  • Do not allow passing the column name to sum when a block is passed.

    Rafael Mendonça França

  • Do not allow passing the column name to count when a block is passed.

    Rafael Mendonça França

  • Remove delegation of missing methods in a relation to arel.

    Rafael Mendonça França

  • Remove delegation of missing methods in a relation to private methods of the class.

    Rafael Mendonça França

  • Deprecate config.activerecord.sqlite3.represent_boolean_as_integer.

    Rafael Mendonça França

  • Change SQLite3Adapter to always represent boolean values as integers.

    Rafael Mendonça França

  • Remove ability to specify a timestamp name for #cache_key.

    Rafael Mendonça França

  • Remove deprecated ActiveRecord::Migrator.migrations_path=.

    Rafael Mendonça França

  • Remove deprecated expand_hash_conditions_for_aggregates.

    Rafael Mendonça França

  • Set polymorphic type column to NULL on dependent: :nullify strategy.

    On polymorphic associations both the foreign key and the foreign type columns will be set to NULL.

    Laerti Papa

  • Allow permitted instance of ActionController::Parameters as argument of ActiveRecord::Relation#exists?.

    Gannon McGibbon

  • Add support for endless ranges introduces in Ruby 2.6.

    Greg Navis

  • Deprecate passing migrations_paths to connection.assume_migrated_upto_version.

    Ryuta Kamizono

  • MySQL: ROW_FORMAT=DYNAMIC create table option by default.

    Since MySQL 5.7.9, the innodb_default_row_format option defines the default row
    format for InnoDB tables. The default setting is DYNAMIC.
    The row format is required for indexing on varchar(255) with utf8mb4 columns.

    Ryuta Kamizono

  • Fix join table column quoting with SQLite.

    Gannon McGibbon

  • Allow disabling scopes generated by ActiveRecord.enum.

    Alfred Dominic

  • Ensure that delete_all on collection proxy returns affected count.

    Ryuta Kamizono

  • Reset scope after delete on collection association to clear stale offsets of removed records.

    Gannon McGibbon

  • Add the ability to prevent writes to a database for the duration of a block.

    Allows the application to prevent writes to a database. This can be useful when
    you're building out multiple databases and want to make sure you're not sending
    writes when you want a read.

    If while_preventing_writes is called and the query is considered a write
    query the database will raise an exception regardless of whether the database
    user is able to write.

    This is not meant to be a catch-all for write queries but rather a way to enforce
    read-only queries without opening a second connection. One purpose of this is to
    catch accidental writes, not all writes.

    Eileen M. Uchitelle

  • Allow aliased attributes to be used in #update_columns and #update.

    Gannon McGibbon

  • Allow spaces in postgres table names.

    Fixes issue where "user post" is misinterpreted as ""user"."post"" when quoting table names with the postgres adapter.

    Gannon McGibbon

  • Cached columns_hash fields should be excluded from ResultSet#column_types

    PR #34528 addresses the inconsistent behaviour when attribute is defined for an ignored column. The following test
    was passing for SQLite and MySQL, but failed for PostgreSQL:

    class DeveloperName < ActiveRecord::Type::String
      def deserialize(value)
        "Developer: #{value}"
      end
    end
    
    class AttributedDeveloper < ActiveRecord::Base
      self.table_name = "developers"
    
      attribute :name, DeveloperName.new
    
      self.ignored_columns += ["name"]
    end
    
    developer = AttributedDeveloper.create
    developer.update_column :name, "name"
    
    loaded_developer = AttributedDeveloper.where(id: developer.id).select("*").first
    puts loaded_developer.name # should be "Developer: name" but it's just "name"
    

    Dmitry Tsepelev

  • Make the implicit order column configurable.

    When calling ordered finder methods such as +first+ or +last+ without an
    explicit order clause, ActiveRecord sorts records by primary key. This can
    result in unpredictable and surprising behaviour when the primary key is
    not an auto-incrementing integer, for example when it's a UUID. This change
    makes it possible to override the column used for implicit ordering such
    that +first+ and +last+ will return more predictable results.

    Example:

    class Project < ActiveRecord::Base
      self.implicit_order_column = "created_at"
    end
    

    Tekin Suleyman

  • Bump minimum PostgreSQL version to 9.3.

    Yasuo Honda

  • Values of enum are frozen, raising an error when attempting to modify them.

    Emmanuel Byrd

  • Move ActiveRecord::StatementInvalid SQL to error property and include binds as separate error property.

    ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception_class now requires binds to be passed as the last argument.

    ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception now requires message, sql, and binds to be passed as keyword arguments.

    Subclasses of ActiveRecord::StatementInvalid must now provide sql: and binds: arguments to super.

    Example:

    class MySubclassedError < ActiveRecord::StatementInvalid
      def initialize(message, sql:, binds:)
        super(message, sql: sql, binds: binds)
      end
    end
    

    Gannon McGibbon

  • Add an :if_not_exists option to create_table.

    Example:

    create_table :posts, if_not_exists: true do |t|
      t.string :title
    end
    

    That would execute:

    CREATE TABLE IF NOT EXISTS posts (
      ...
    )
    

    If the table already exists, if_not_exists: false (the default) raises an
    exception whereas if_not_exists: true does nothing.

    fatkodima, Stefan Kanev

  • Defining an Enum as a Hash with blank key, or as an Array with a blank value, now raises an ArgumentError.

    Christophe Maximin

  • Adds support for multiple databases to rails db:schema:cache:dump and rails db:schema:cache:clear.

    Gannon McGibbon

  • update_columns now correctly raises ActiveModel::MissingAttributeError
    if the attribute does not exist.

    Sean Griffin

  • Add support for hash and url configs in database hash of ActiveRecord::Base.connected_to.

    User.connected_to(database: { writing: "postgres://foo" }) do
      User.create!(name: "Gannon")
    end
    
    config = { "adapter" => "sqlite3", "database" => "db/readonly.sqlite3" }
    User.connected_to(database: { reading: config }) do
      User.count
    end
    

    Gannon McGibbon

  • Support default expression for MySQL.

    MySQL 8.0.13 and higher supports default value to be a function or expression.

    https://dev.mysql.com/doc/refman/8.0/en/create-table.html

    Ryuta Kamizono

  • Support expression indexes for MySQL.

    MySQL 8.0.13 and higher supports functional key parts that index
    expression values rather than column or column prefix values.

    https://dev.mysql.com/doc/refman/8.0/en/create-index.html

    Ryuta Kamizono

  • Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error.

    Fixes #33056.

    Federico Martinez

  • Add basic API for connection switching to support multiple databases.

    1. Adds a connects_to method for models to connect to multiple databases. Example:
    class AnimalsModel < ApplicationRecord
      self.abstract_class = true
    
      connects_to database: { writing: :animals_primary, reading: :animals_replica }
    end
    
    class Dog < AnimalsModel
      # connected to both the animals_primary db for writing and the animals_replica for reading
    end
    
    1. Adds a connected_to block method for switching connection roles or connecting to
      a database that the model didn't connect to. Connecting to the database in this block is
      useful when you have another defined connection, for example slow_replica that you don't
      want to connect to by default but need in the console, or a specific code block.
    ActiveRecord::Base.connected_to(role: :reading) do
      Dog.first # finds dog from replica connected to AnimalsBase
      Book.first # doesn't have a reading connection, will raise an error
    end
    
    ActiveRecord::Base.connected_to(database: :slow_replica) do
      SlowReplicaModel.first # if the db config has a slow_replica configuration this will be used to do the lookup, otherwise this will throw an exception
    end
    

    Eileen M. Uchitelle

  • Enum raises on invalid definition values

    When defining a Hash enum it can be easy to use [] instead of {}. This
    commit checks that only valid definition values are provided, those can
    be a Hash, an array of Symbols or an array of Strings. Otherwise it
    raises an ArgumentError.

    Fixes #33961

    Alberto Almagro

  • Reloading associations now clears the Query Cache like Persistence#reload does.

    class Post < ActiveRecord::Base
      has_one :category
      belongs_to :author
      has_many :comments
    end
    
    # Each of the following will now clear the query cache.
    post.reload_category
    post.reload_author
    post.comments.reload
    

    Christophe Maximin

  • Added index option for change_table migration helpers.
    With this change you can create indexes while adding new
    columns into the existing tables.

    Example:

    change_table(:languages) do |t|
      t.string :country_code, index: true
    end
    

    Mehmet Emin İNAÇ

  • Fix transaction reverting for migrations.

    Before: Commands inside a transaction in a reverted migration ran uninverted.
    Now: This change fixes that by reverting commands inside transaction block.

    fatkodima, David Verhasselt

  • Raise an error instead of scanning the filesystem root when fixture_path is blank.

    Gannon McGibbon, Max Albrecht

  • Allow ActiveRecord::Base.configurations= to be set with a symbolized hash.

    Gannon McGibbon

  • Don't update counter cache unless the record is actually saved.

    Fixes #31493, #33113, #33117.

    Ryuta Kamizono

  • Deprecate ActiveRecord::Result#to_hash in favor of ActiveRecord::Result#to_a.

    Gannon McGibbon, Kevin Cheng

  • SQLite3 adapter supports expression indexes.

    create_table :users do |t|
      t.string :email
    end
    
    add_index :users, 'lower(email)', name: 'index_users_on_email', unique: true
    

    Gray Kemmey

  • Allow subclasses to redefine autosave callbacks for associated records.

    Fixes #33305.

    Andrey Subbota

  • Bump minimum MySQL version to 5.5.8.

    Yasuo Honda

  • Use MySQL utf8mb4 character set by default.

    utf8mb4 character set with 4-Byte encoding supports supplementary characters including emoji.
    The previous default 3-Byte encoding character set utf8 is not enough to support them.

    Yasuo Honda

  • Fix duplicated record creation when using nested attributes with create_with.

    Darwin Wu

  • Configuration item config.filter_parameters could also filter out
    sensitive values of database columns when call #inspect.
    We also added ActiveRecord::Base::filter_attributes/= in order to
    specify sensitive attributes to specific model.

    Rails.application.config.filter_parameters += [:credit_card_number, /phone/]
    Account.last.inspect # => #<Account id: 123, name: "DHH", credit_card_number: [FILTERED], telephone_number: [FILTERED] ...>
    SecureAccount.filter_attributes += [:name]
    SecureAccount.last.inspect # => #<SecureAccount id: 42, name: [FILTERED], credit_card_number: [FILTERED] ...>
    

    Zhang Kang, Yoshiyuki Kinjo

  • Deprecate column_name_length, table_name_length, columns_per_table,
    indexes_per_table, columns_per_multicolumn_index, sql_query_length,
    and joins_per_query methods in DatabaseLimits.

    Ryuta Kamizono

  • ActiveRecord::Base.configurations now returns an object.

    ActiveRecord::Base.configurations used to return a hash, but this
    is an inflexible data model. In order to improve multiple-database
    handling in Rails, we've changed this to return an object. Some methods
    are provided to make the object behave hash-like in order to ease the
    transition process. Since most applications don't manipulate the hash
    we've decided to add backwards-compatible functionality that will throw
    a deprecation warning if used, however calling ActiveRecord::Base.configurations
    will use the new version internally and externally.

    For example, the following database.yml:

    development:
      adapter: sqlite3
      database: db/development.sqlite3
    

    Used to become a hash:

    { "development" => { "adapter" => "sqlite3", "database" => "db/development.sqlite3" } }
    

    Is now converted into the following object:

    #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[
      #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",
        @spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>
      ]
    

    Iterating over the database configurations has also changed. Instead of
    calling hash methods on the configurations hash directly, a new method configs_for has
    been provided that allows you to select the correct configuration. env_name, and
    spec_name arguments are optional. For example these return an array of
    database config objects for the requested environment and a single database config object
    will be returned for the requested environment and specification name respectively.

    ActiveRecord::Base.configurations.configs_for(env_name: "development")
    ActiveRecord::Base.configurations.configs_for(env_name: "development", spec_name: "primary")
    

    Eileen M. Uchitelle, Aaron Patterson

  • Add database configuration to disable advisory locks.

    production:
      adapter: postgresql
      advisory_locks: false
    

    Guo Xiang

  • SQLite3 adapter alter_table method restores foreign keys.

    Yasuo Honda

  • Allow :to_table option to invert_remove_foreign_key.

    Example:

    remove_foreign_key :accounts, to_table: :owners

    Nikolay Epifanov, Rich Chen

  • Add environment & load_config dependency to bin/rake db:seed to enable
    seed load in environments without Rails and custom DB configuration

    Tobias Bielohlawek

  • Fix default value for mysql time types with specified precision.

    Nikolay Kondratyev

  • Fix touch option to behave consistently with Persistence#touch method.

    Ryuta Kamizono

  • Migrations raise when duplicate column definition.

    Fixes #33024.

    Federico Martinez

  • Bump minimum SQLite version to 3.8

    Yasuo Honda

  • Fix parent record should not get saved with duplicate children records.

    Fixes #32940.

    Santosh Wadghule

  • Fix logic on disabling commit callbacks so they are not called unexpectedly when errors occur.

    Brian Durand

  • Ensure Associations::CollectionAssociation#size and Associations::CollectionAssociation#empty?
    use loaded association ids if present.

    Graham Turner

  • Add support to preload associations of polymorphic associations when not all the records have the requested associations.

    Dana Sherson

  • Add touch_all method to ActiveRecord::Relation.

    Example:

    Person.where(name: "David").touch_all(time: Time.new(2020, 5, 16, 0, 0, 0))
    

    fatkodima, duggiefresh

  • Add ActiveRecord::Base.base_class? predicate.

    Bogdan Gusiev

  • Add custom prefix/suffix options to ActiveRecord::Store.store_accessor.

    Tan Huynh, Yukio Mizuta

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

  • Deprecate update_attributes/! in favor of update/!.

    Eddie Lebow

  • Add ActiveRecord::Base.create_or_find_by/! to deal with the SELECT/INSERT race condition in
    ActiveRecord::Base.find_or_create_by/! by leaning on unique constraints in the database.

    DHH

  • Add Relation#pick as short-hand for single-value plucks.

    DHH

Action View

  • Remove deprecated image_alt helper.

    Rafael Mendonça França

  • Fix the need of #protect_against_forgery? method defined in
    ActionView::Base subclasses. This prevents the use of forms and buttons.

    Genadi Samokovarov

  • Fix UJS permanently showing disabled text in a[data-remote][data-disable-with] elements within forms.
    Fixes #33889

    Wolfgang Hobmaier

  • Prevent non-primary mouse keys from triggering Rails UJS click handlers.
    Firefox fires click events even if the click was triggered by non-primary mouse keys such as right- or scroll-wheel-clicks.
    For example, right-clicking a link such as the one described below (with an underlying ajax request registered on click) should not cause that request to occur.

    <%= link_to 'Remote', remote_path, class: 'remote', remote: true, data: { type: :json } %>
    

    Fixes #34541

    Wolfgang Hobmaier

  • Prevent ActionView::TextHelper#word_wrap from unexpectedly stripping white space from the left side of lines.

    For example, given input like this:

        This is a paragraph with an initial indent,
    followed by additional lines that are not indented,
    and finally terminated with a blockquote:
      "A pithy saying"
    

    Calling word_wrap should not trim the indents on the first and last lines.

    Fixes #34487

    Lyle Mullican

  • Add allocations to template rendering instrumentation.

    Adds the allocations for template and partial rendering to the server output on render.

      Rendered posts/_form.html.erb (Duration: 7.1ms | Allocations: 6004)
      Rendered posts/new.html.erb within layouts/application (Duration: 8.3ms | Allocations: 6654)
    Completed 200 OK in 858ms (Views: 848.4ms | ActiveRecord: 0.4ms | Allocations: 1539564)
    

    Eileen M. Uchitelle, Aaron Patterson

  • Respect the only_path option passed to url_for when the options are passed in as an array

    Fixes #33237.

    Joel Ambass

  • Deprecate calling private model methods from view helpers.

    For example, in methods like options_from_collection_for_select
    and collection_select it is possible to call private methods from
    the objects used.

    Fixes #33546.

    Ana María Martínez Gómez

  • Fix issue with button_to's to_form_params

    button_to was throwing exception when invoked with params hash that
    contains symbol and string keys. The reason for the exception was that
    to_form_params was comparing the given symbol and string keys.

    The issue is fixed by turning all keys to strings inside
    to_form_params before comparing them.

    Georgi Georgiev

  • Mark arrays of translations as trusted safe by using the _html suffix.

    Example:

    en:
      foo_html:
        - "One"
        - "<strong>Two</strong>"
        - "Three &#128075; &#128578;"
    

    Juan Broullon

  • Add year_format option to date_select tag. This option makes it possible to customize year
    names. Lambda should be passed to use this option.

    Example:

    date_select('user_birthday', '', start_year: 1998, end_year: 2000, year_format: ->year { "Heisei #{year - 1988}" })
    

    The HTML produced:

    <select id="user_birthday__1i" name="user_birthday[(1i)]">
    <option value="1998">Heisei 10</option>
    <option value="1999">Heisei 11</option>
    <option value="2000">Heisei 12</option>
    </select>
    /* The rest is omitted */
    

    Koki Ryu

  • Fix JavaScript views rendering does not work with Firefox when using
    Content Security Policy.

    Fixes #32577.

    Yuji Yaginuma

  • Add the nonce: true option for javascript_include_tag helper to
    support automatic nonce generation for Content Security Policy.
    Works the same way as javascript_tag nonce: true does.

    Yaroslav Markin

  • Remove ActionView::Helpers::RecordTagHelper.

    Yoshiyuki Hirano

  • Disable ActionView::Template finalizers in test environment.

    Template finalization can be expensive in large view test suites.
    Add a configuration option,
    action_view.finalize_compiled_template_methods, and turn it off in
    the test environment.

    Simon Coffey

  • Extract the confirm call in its own, overridable method in rails_ujs.

    Example:

    Rails.confirm = function(message, element) {
      return (my_bootstrap_modal_confirm(message));
    }
    

    Mathieu Mahé

  • Enable select tag helper to mark prompt option as selected and/or disabled for required
    field.

    Example:

    select :post,
           :category,
           ["lifestyle", "programming", "spiritual"],
           { selected: "", disabled: "", prompt: "Choose one" },
           { required: true }
    

    Placeholder option would be selected and disabled.

    The HTML produced:

    <select required="required" name="post[category]" id="post_category">
    <option disabled="disabled" selected="selected" value="">Choose one</option>
    <option value="lifestyle">lifestyle</option>
    <option value="programming">programming</option>
    <option value="spiritual">spiritual</option></select>
    

    Sergey Prikhodko

  • Don't enforce UTF-8 by default.

    With the disabling of TLS 1.0 by most major websites, continuing to run
    IE8 or lower becomes increasingly difficult so default to not enforcing
    UTF-8 encoding as it's not relevant to other browsers.

    Andrew White

  • Change translation key of submit_tag from module_name_class_name to module_name/class_name.

    Rui Onodera

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

Action Pack

  • Remove deprecated fragment_cache_key helper in favor of combined_fragment_cache_key.

    Rafael Mendonça França

  • Remove deprecated methods in ActionDispatch::TestResponse.

    #success?, missing? and error? were deprecated in Rails 5.2 in favor of
    #successful?, not_found? and server_error?.

    Rafael Mendonça França

  • Ensure external redirects are explicitly allowed

    Add fallback_location and allow_other_host options to redirect_to.

    Gannon McGibbon

  • Introduce ActionDispatch::HostAuthorization

    This is a new middleware that guards against DNS rebinding attacks by
    white-listing the allowed hosts a request can be made to.

    Each host is checked with the case operator (#===) to support RegExp,
    Proc, IPAddr and custom objects as host allowances.

    Genadi Samokovarov

  • Allow using parsed_body in ActionController::TestCase.

    In addition to ActionDispatch::IntegrationTest, allow using
    parsed_body in ActionController::TestCase:

    class SomeControllerTest < ActionController::TestCase
      def test_some_action
        post :action, body: { foo: 'bar' }
        assert_equal({ "foo" => "bar" }, response.parsed_body)
      end
    end
    

    Fixes #34676.

    Tobias Bühlmann

  • Raise an error on root route naming conflicts.

    Raises an ArgumentError when multiple root routes are defined in the
    same context instead of assigning nil names to subsequent roots.

    Gannon McGibbon

  • Allow rescue from parameter parse errors:

    rescue_from ActionDispatch::Http::Parameters::ParseError do
      head :unauthorized
    end
    

    Gannon McGibbon, Josh Cheek

  • Reset Capybara sessions if failed system test screenshot raising an exception.

    Reset Capybara sessions if take_failed_screenshot raise exception
    in system test after_teardown.

    Maxim Perepelitsa

  • Use request object for context if there's no controller

    There is no controller instance when using a redirect route or a
    mounted rack application so pass the request object as the context
    when resolving dynamic CSP sources in this scenario.

    Fixes #34200.

    Andrew White

  • Apply mapping to symbols returned from dynamic CSP sources

    Previously if a dynamic source returned a symbol such as :self it
    would be converted to a string implicity, e.g:

    policy.default_src -> { :self }
    

    would generate the header:

    Content-Security-Policy: default-src self
    

    and now it generates:

    Content-Security-Policy: default-src 'self'
    

    Andrew White

  • Add ActionController::Parameters#each_value.

    Lukáš Zapletal

  • Deprecate ActionDispatch::Http::ParameterFilter in favor of ActiveSupport::ParameterFilter.

    Yoshiyuki Kinjo

  • Encode Content-Disposition filenames on send_data and send_file.
    Previously, send_data 'data', filename: "\u{3042}.txt" sends
    "filename=\"\u{3042}.txt\"" as Content-Disposition and it can be
    garbled.
    Now it follows RFC 2231 and
    RFC 5987 and sends
    "filename=\"%3F.txt\"; filename*=UTF-8''%E3%81%82.txt".
    Most browsers can find filename correctly and old browsers fallback to ASCII
    converted name.

    Fumiaki Matsushima

  • Expose ActionController::Parameters#each_key which allows iterating over
    keys without allocating an array.

    Richard Schneeman

  • Purpose metadata for signed/encrypted cookies.

    Rails can now thwart attacks that attempt to copy signed/encrypted value
    of a cookie and use it as the value of another cookie.

    It does so by stashing the cookie-name in the purpose field which is
    then signed/encrypted along with the cookie value. Then, on a server-side
    read, we verify the cookie-names and discard any attacked cookies.

    Enable action_dispatch.use_cookies_with_metadata to use this feature, which
    writes cookies with the new purpose and expiry metadata embedded.

    Assain Jaleel

  • Raises ActionController::RespondToMismatchError with confliciting respond_to invocations.

    respond_to can match multiple types and lead to undefined behavior when
    multiple invocations are made and the types do not match:

    respond_to do |outer_type|
      outer_type.js do
        respond_to do |inner_type|
          inner_type.html { render body: "HTML" }
        end
      end
    end
    

    Patrick Toomey

  • ActionDispatch::Http::UploadedFile now delegates to_path to its tempfile.

    This allows uploaded file objects to be passed directly to File.read
    without raising a TypeError:

    uploaded_file = ActionDispatch::Http::UploadedFile.new(tempfile: tmp_file)
    File.read(uploaded_file)
    

    Aaron Kromer

  • Pass along arguments to underlying get method in follow_redirect!.

    Now all arguments passed to follow_redirect! are passed to the underlying
    get method. This for example allows to set custom headers for the
    redirection request to the server.

    follow_redirect!(params: { foo: :bar })
    

    Remo Fritzsche

  • Introduce a new error page to when the implicit render page is accessed in the browser.

    Now instead of showing an error page that with exception and backtraces we now show only
    one informative page.

    Vinicius Stock

  • Introduce ActionDispatch::DebugExceptions.register_interceptor.

    Exception aware plugin authors can use the newly introduced
    .register_interceptor method to get the processed exception, instead of
    monkey patching DebugExceptions.

    ActionDispatch::DebugExceptions.register_interceptor do |request, exception|
      HypoteticalPlugin.capture_exception(request, exception)
    end
    

    Genadi Samokovarov

  • Output only one Content-Security-Policy nonce header value per request.

    Fixes #32597.

    Andrey Novikov, Andrew White

  • Move default headers configuration into their own module that can be included in controllers.

    Kevin Deisz

  • Add method dig to session.

    claudiob, Takumi Shotoku

  • Controller level force_ssl has been deprecated in favor of
    config.force_ssl.

    Derek Prior

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

Active Job

  • Return false instead of the job instance when enqueue is aborted.

    This will be the behavior in Rails 6.1 but it can be controlled now with
    config.active_job.return_false_on_aborted_enqueue.

    Kir Shatrov

  • Keep executions for each specific declaration

    Each retry_on declaration has now its own specific executions counter. Before it was
    shared between all executions of a job.

    Alberto Almagro

  • Allow all assertion helpers that have a only and except keyword to accept
    Procs.

    Edouard Chin

  • Restore HashWithIndifferentAccess support to ActiveJob::Arguments.deserialize.

    Gannon McGibbon

  • Include deserialized arguments in job instances returned from
    assert_enqueued_with and assert_performed_with

    Alan Wu

  • Allow assert_enqueued_with/assert_performed_with methods to accept
    a proc for the args argument. This is useful to check if only a subset of arguments
    matches your expectations.

    Edouard Chin

  • ActionDispatch::IntegrationTest includes ActiveJob::TestHelper module by default.

    Ricardo Díaz

  • Added enqueue_retry.active_job, retry_stopped.active_job, and discard.active_job hooks.

    steves

  • Allow assert_performed_with to be called without a block.

    bogdanvlviv

  • Execution of assert_performed_jobs, and assert_no_performed_jobs
    without a block should respect passed :except, :only, and :queue options.

    bogdanvlviv

  • Allow :queue option to job assertions and helpers.

    bogdanvlviv

  • Allow perform_enqueued_jobs to be called without a block.

    Performs all of the jobs that have been enqueued up to this point in the test.

    Kevin Deisz

  • Move enqueue/enqueue_at notifications to an around callback.

    Improves timing accuracy over the old after callback by including
    time spent writing to the adapter's IO implementation.

    Zach Kemp

  • Allow call assert_enqueued_with with no block.

    Example:

    def test_assert_enqueued_with
      MyJob.perform_later(1,2,3)
      assert_enqueued_with(job: MyJob, args: [1,2,3], queue: 'low')
    
      MyJob.set(wait_until: Date.tomorrow.noon).perform_later
      assert_enqueued_with(job: MyJob, at: Date.tomorrow.noon)
    end
    

    bogdanvlviv

  • Allow passing multiple exceptions to retry_on, and discard_on.

    George Claghorn

  • Pass the error instance as the second parameter of block executed by discard_on.

    Fixes #32853.

    Yuji Yaginuma

  • Remove support for Qu gem.

    Reasons are that the Qu gem wasn't compatible since Rails 5.1,
    gem development was stopped in 2014 and maintainers have
    confirmed its demise. See issue #32273

    Alberto Almagro

  • Add support for timezones to Active Job.

    Record what was the current timezone in effect when the job was
    enqueued and then restore when the job is executed in same way
    that the current locale is recorded and restored.

    Andrew White

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

  • Add support to define custom argument serializers.

    Evgenii Pecherkin, Rafael Mendonça França

Action Mailer

  • Deprecate ActionMailer::Base.receive in favor of Action Mailbox.

    George Claghorn

  • Add MailDeliveryJob for delivering both regular and parameterized mail. Deprecate using DeliveryJob and Parameterized::DeliveryJob.

    Gannon McGibbon

  • Fix ActionMailer assertions not working when a Mail defines
    a custom delivery job class

    Edouard Chin

  • Mails with multipart format blocks with implicit render now also check for
    a template name in options hash instead of only using the action name.

    Marcus Ilgner

  • ActionDispatch::IntegrationTest includes ActionMailer::TestHelper module by default.

    Ricardo Díaz

  • Add perform_deliveries to a payload of deliver.action_mailer notification.

    Yoshiyuki Kinjo

  • Change delivery logging message when perform_deliveries is false.

    Yoshiyuki Kinjo

  • Allow call assert_enqueued_email_with with no block.

    Example:

    def test_email
      ContactMailer.welcome.deliver_later
      assert_enqueued_email_with ContactMailer, :welcome
    end
    
    def test_email_with_arguments
      ContactMailer.welcome("Hello", "Goodbye").deliver_later
      assert_enqueued_email_with ContactMailer, :welcome, args: ["Hello", "Goodbye"]
    end
    

    bogdanvlviv

  • Ensure mail gem is eager autoloaded when eager load is true to prevent thread deadlocks.

    Samuel Cochran

  • Perform email jobs in assert_emails.

    Gannon McGibbon

  • Add Base.unregister_observer, Base.unregister_observers,
    Base.unregister_interceptor, Base.unregister_interceptors,
    Base.unregister_preview_interceptor and Base.unregister_preview_interceptors.
    This makes it possible to dynamically add and remove email observers and
    interceptors at runtime in the same way they're registered.

    Claudio Ortolina, Kota Miyake

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

Action Cable

  • Merge action-cable-testing to Rails.

    Vladimir Dementyev

  • The JavaScript WebSocket client will no longer try to reconnect
    when you call reject_unauthorized_connection on the connection.

    Mick Staugaard

  • ActionCable.Connection#getState now references the configurable
    ActionCable.adapters.WebSocket property rather than the WebSocket global
    variable, matching the behavior of ActionCable.Connection#open.

    Richard Macklin

  • The ActionCable javascript package has been converted from CoffeeScript
    to ES2015, and we now publish the source code in the npm distribution.

    This allows ActionCable users to depend on the javascript source code
    rather than the compiled code, which can produce smaller javascript bundles.

    This change includes some breaking changes to optional parts of the
    ActionCable javascript API:

    • Configuration of the WebSocket adapter and logger adapter have been moved
      from properties of ActionCable to properties of ActionCable.adapters.
      If you are currently configuring these adapters you will need to make
      these changes when upgrading:

      -    ActionCable.WebSocket = MyWebSocket
      +    ActionCable.adapters.WebSocket = MyWebSocket
      
      -    ActionCable.logger = myLogger
      +    ActionCable.adapters.logger = myLogger
      
    • The ActionCable.startDebugging() and ActionCable.stopDebugging()
      methods have been removed and replaced with the property
      ActionCable.logger.enabled. If you are currently using these methods you
      will need to make these changes when upgrading:

      -    ActionCable.startDebugging()
      +    ActionCable.logger.enabled = true
      
      -    ActionCable.stopDebugging()
      +    ActionCable.logger.enabled = false
      

    Richard Macklin

  • Add id option to redis adapter so now you can distinguish
    ActionCable's redis connections among others. Also, you can set
    custom id in options.

    Before:

    $ redis-cli client list
    id=669 addr=127.0.0.1:46442 fd=8 name= age=18 ...
    

    After:

    $ redis-cli client list
    id=673 addr=127.0.0.1:46516 fd=8 name=ActionCable-PID-19413 age=2 ...
    

    Ilia Kasianenko

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

Active Storage

  • Replace config.active_storage.queue with two options that indicate which
    queues analysis and purge jobs should use, respectively:

    • config.active_storage.queues.analysis
    • config.active_storage.queues.purge

    config.active_storage.queue is preferred over the new options when it's
    set, but it is deprecated and will be removed in Rails 6.1.

    George Claghorn

  • Permit generating variants of TIFF images.

    Luciano Sousa

  • Use base36 (all lowercase) for all new Blob keys to prevent
    collisions and undefined behavior with case-insensitive filesystems and
    database indices.

    Julik Tarkhanov

  • It doesn’t include an X-CSRF-Token header if a meta tag is not found on
    the page. It previously included one with a value of undefined.

    Cameron Bothner

  • Fix ArgumentError when uploading to amazon s3

    Hiroki Sanpei

  • Add progressive JPG to default list of variable content types

    Maurice Kühlborn

  • Add ActiveStorage.routes_prefix for configuring generated routes.

    Chris Bisnett

  • ActiveStorage::Service::AzureStorageService only handles specifically
    relevant types of Azure::Core::Http::HTTPError. It previously obscured
    other types of HTTPError, which is the azure-storage gem’s catch-all
    exception class.

    Cameron Bothner

  • ActiveStorage::DiskController#show generates a 404 Not Found response when
    the requested file is missing from the disk service. It previously raised
    Errno::ENOENT.

    Cameron Bothner

  • ActiveStorage::Blob#download and ActiveStorage::Blob#open raise
    ActiveStorage::FileNotFoundError when the corresponding file is missing
    from the storage service. Services translate service-specific missing object
    exceptions (e.g. Google::Cloud::NotFoundError for the GCS service and
    Errno::ENOENT for the disk service) into
    ActiveStorage::FileNotFoundError.

    Cameron Bothner

  • Added the ActiveStorage::SetCurrent concern for custom Active Storage
    controllers that can't inherit from ActiveStorage::BaseController.

    George Claghorn

  • Active Storage error classes like ActiveStorage::IntegrityError and
    ActiveStorage::UnrepresentableError now inherit from ActiveStorage::Error
    instead of StandardError. This permits rescuing ActiveStorage::Error to
    handle all Active Storage errors.

    Andrei Makarov, George Claghorn

  • Uploaded files assigned to a record are persisted to storage when the record
    is saved instead of immediately.

    In Rails 5.2, the following causes an uploaded file in params[:avatar] to
    be stored:

    @user.avatar = params[:avatar]
    

    In Rails 6, the uploaded file is stored when @user is successfully saved.

    George Claghorn

  • Add the ability to reflect on defined attachments using the existing
    ActiveRecord reflection mechanism.

    Kevin Deisz

  • Variant arguments of false or nil will no longer be passed to the
    processor. For example, the following will not have the monochrome
    variation applied:

      avatar.variant(monochrome: false)
    

    Jacob Smith

  • Generated attachment getter and setter methods are created
    within the model's GeneratedAssociationMethods module to
    allow overriding and composition using super.

    Josh Susser, Jamon Douglas

  • Add ActiveStorage::Blob#open, which downloads a blob to a tempfile on disk
    and yields the tempfile. Deprecate ActiveStorage::Downloading.

    David Robertson, George Claghorn

  • Pass in identify: false as an argument when providing a content_type for
    ActiveStorage::Attached::{One,Many}#attach to bypass automatic content
    type inference. For example:

      @message.image.attach(
        io: File.open('/path/to/file'),
        filename: 'file.pdf',
        content_type: 'application/pdf',
        identify: false
      )
    

    Ryan Davidson

  • The Google Cloud Storage service properly supports streaming downloads.
    It now requires version 1.11 or newer of the google-cloud-storage gem.

    George Claghorn

  • Use the ImageProcessing gem
    for Active Storage variants, and deprecate the MiniMagick backend.

    This means that variants are now automatically oriented if the original
    image was rotated. Also, in addition to the existing ImageMagick
    operations, variants can now use :resize_to_fit, :resize_to_fill, and
    other ImageProcessing macros. These are now recommended over raw :resize,
    as they also sharpen the thumbnail after resizing.

    The ImageProcessing gem also comes with a backend implemented on
    libvips, an alternative to
    ImageMagick which has significantly better performance than
    ImageMagick in most cases, both in terms of speed and memory usage. In
    Active Storage it's now possible to switch to the libvips backend by
    changing Rails.application.config.active_storage.variant_processor to
    :vips.

    Janko Marohnić

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

Action Mailbox

  • Added to Rails.

    DHH

Action Text

  • Added to Rails.

    DHH

Railties

  • Remove deprecated after_bundle helper inside plugins templates.

    Rafael Mendonça França

  • Remove deprecated support to old config.ru that use the application class as argument of run.

    Rafael Mendonça França

  • Remove deprecated environment argument from the rails commands.

    Rafael Mendonça França

  • Remove deprecated capify!.

    Rafael Mendonça França

  • Remove deprecated config.secret_token.

    Rafael Mendonça França

  • Seed database with inline ActiveJob job adapter.

    Gannon McGibbon

  • Add rails db:system:change command for changing databases.

    bin/rails db:system:change --to=postgresql
       force  config/database.yml
        gsub  Gemfile
    

    The change command copies a template config/database.yml with the target database adapter into your app, and replaces your database gem with the target database gem.

    Gannon McGibbon

  • Add rails test:channels.

    bogdanvlviv

  • Use original bundler environment variables during the process of generating a new rails project.

    Marco Costa

  • Send Active Storage analysis and purge jobs to dedicated queues by default.

    Analysis jobs now use the :active_storage_analysis queue, and purge jobs
    now use the :active_storage_purge queue. This matches Action Mailbox,
    which sends its jobs to dedicated queues by default.

    George Claghorn

  • Add rails test:mailboxes.

    George Claghorn

  • Introduce guard against DNS rebinding attacks

    The ActionDispatch::HostAuthorization is a new middleware that prevent
    against DNS rebinding and other Host header attacks. It is included in
    the development environment by default with the following configuration:

    Rails.application.config.hosts = [
      IPAddr.new("0.0.0.0/0"), # All IPv4 addresses.
      IPAddr.new("::/0"),      # All IPv6 addresses.
      "localhost"              # The localhost reserved domain.
    ]
    

    In other environments Rails.application.config.hosts is empty and no
    Host header checks will be done. If you want to guard against header
    attacks on production, you have to manually whitelist the allowed hosts
    with:

    Rails.application.config.hosts << "product.com"
    

    The host of a request is checked against the hosts entries with the case
    operator (#===), which lets hosts support entries of type RegExp,
    Proc and IPAddr to name a few. Here is an example with a regexp.

    # Allow requests from subdomains like `www.product.com` and
    # `beta1.product.com`.
    Rails.application.config.hosts << /.*\.product\.com/
    

    A special case is supported that allows you to whitelist all sub-domains:

    # Allow requests from subdomains like `www.product.com` and
    # `beta1.product.com`.
    Rails.application.config.hosts << ".product.com"
    

    Genadi Samokovarov

  • Remove redundant suffixes on generated helpers.

    Gannon McGibbon

  • Remove redundant suffixes on generated integration tests.

    Gannon McGibbon

  • Fix boolean interaction in scaffold system tests.

    Gannon McGibbon

  • Remove redundant suffixes on generated system tests.

    Gannon McGibbon

  • Add an abort_on_failure boolean option to the generator method that shell
    out (generate, rake, rails_command) to abort the generator if the
    command fails.

    David Rodríguez

  • Remove app/assets and app/javascript from eager_load_paths and autoload_paths.

    Gannon McGibbon

  • Use Ids instead of memory addresses when displaying references in scaffold views.

    Fixes #29200.

    Rasesh Patel

  • Adds support for multiple databases to rails db:migrate:status.
    Subtasks are also added to get the status of individual databases (eg. rails db:migrate:status:animals).

    Gannon McGibbon

  • Use Webpacker by default to manage app-level JavaScript through the new app/javascript directory.
    Sprockets is now solely in charge, by default, of compiling CSS and other static assets.
    Action Cable channel generators will create ES6 stubs rather than use CoffeeScript.
    Active Storage, Action Cable, Turbolinks, and Rails-UJS are loaded by a new application.js pack.
    Generators no longer generate JavaScript stubs.

    DHH, Lachlan Sylvester

  • Add database (aliased as db) option to model generator to allow
    setting the database. This is useful for applications that use
    multiple databases and put migrations per database in their own directories.

    bin/rails g model Room capacity:integer --database=kingston
          invoke  active_record
          create    db/kingston_migrate/20180830151055_create_rooms.rb
    

    Because rails scaffolding uses the model generator, you can
    also specify a database with the scaffold generator.

    Gannon McGibbon

  • Raise an error when "recyclable cache keys" are being used by a cache store
    that does not explicitly support it. Custom cache keys that do support this feature
    can bypass this error by implementing the supports_cache_versioning? method on their
    class and returning a truthy value.

    Richard Schneeman

  • Support environment specific credentials overrides.

    So any environment will look for config/credentials/#{Rails.env}.yml.enc and fall back
    to config/credentials.yml.enc.

    The encryption key can be in ENV["RAILS_MASTER_KEY"] or config/credentials/production.key.

    Environment credentials overrides can be edited with rails credentials:edit --environment production.
    If no override is setup for the passed environment, it will be created.

    Additionally, the default lookup paths can be overwritten with these configs:

    • config.credentials.content_path
    • config.credentials.key_path

    Wojciech Wnętrzak

  • Make ActiveSupport::Cache::NullStore the default cache store in the test environment.

    Michael C. Nelson

  • Emit warning for unknown inflection rule when generating model.

    Yoshiyuki Kinjo

  • Add database (aliased as db) option to migration generator.

    If you're using multiple databases and have a folder for each database
    for migrations (ex db/migrate and db/new_db_migrate) you can now pass the
    --database option to the generator to make sure the the migration
    is inserted into the correct folder.

    rails g migration CreateHouses --database=kingston
      invoke  active_record
      create    db/kingston_migrate/20180830151055_create_houses.rb
    

    Eileen M. Uchitelle

  • Deprecate rake routes in favor of rails routes.

    Yuji Yaginuma

  • Deprecate rake initializers in favor of rails initializers.

    Annie-Claude Côté

  • Deprecate rake dev:cache in favor of rails dev:cache.

    Annie-Claude Côté

  • Deprecate rails notes subcommands in favor of passing an annotations argument to rails notes.

    The following subcommands are replaced by passing --annotations or -a to rails notes:

    • rails notes:custom ANNOTATION=custom is deprecated in favor of using rails notes -a custom.
    • rails notes:optimize is deprecated in favor of using rails notes -a OPTIMIZE.
    • rails notes:todo is deprecated in favor of usingrails notes -a TODO.
    • rails notes:fixme is deprecated in favor of using rails notes -a FIXME.

    Annie-Claude Côté

  • Deprecate SOURCE_ANNOTATION_DIRECTORIES environment variable used by rails notes
    through Rails::SourceAnnotationExtractor::Annotation in favor of using config.annotations.register_directories.

    Annie-Claude Côté

  • Deprecate rake notes in favor of rails notes.

    Annie-Claude Côté

  • Don't generate unused files in app:update task.

    Skip the assets' initializer when sprockets isn't loaded.

    Skip config/spring.rb when spring isn't loaded.

    Skip yarn's contents when yarn integration isn't used.

    Tsukuru Tanimichi

  • Make the master.key file read-only for the owner upon generation on
    POSIX-compliant systems.

    Previously:

    $ ls -l config/master.key
    -rw-r--r--   1 owner  group      32 Jan 1 00:00 master.key
    

    Now:

    $ ls -l config/master.key
    -rw-------   1 owner  group      32 Jan 1 00:00 master.key
    

    Fixes #32604.

    Jose Luis Duran

  • Deprecate support for using the HOST environment to specify the server IP.

    The BINDING environment should be used instead.

    Fixes #29516.

    Yuji Yaginuma

  • Deprecate passing Rack server name as a regular argument to rails server.

    Previously:

    $ bin/rails server thin
    

    There wasn't an explicit option for the Rack server to use, now we have the
    --using option with the -u short switch.

    Now:

    $ bin/rails server -u thin
    

    This change also improves the error message if a missing or mistyped rack
    server is given.

    Genadi Samokovarov

  • Add "rails routes --expanded" option to output routes in expanded mode like
    "psql --expanded". Result looks like:

    $ rails routes --expanded
    --[ Route 1 ]------------------------------------------------------------
    Prefix            | high_scores
    Verb              | GET
    URI               | /high_scores(.:format)
    Controller#Action | high_scores#index
    --[ Route 2 ]------------------------------------------------------------
    Prefix            | new_high_score
    Verb              | GET
    URI               | /high_scores/new(.:format)
    Controller#Action | high_scores#new
    

    Benoit Tigeot

  • Rails 6 requires Ruby 2.5.0 or newer.

    Jeremy Daer, Kasper Timm Hansen

- Ruby
Published by rafaelfranca over 7 years ago

https://github.com/rails/rails - 5.2.2

Active Support

  • Fix bug where #to_options for ActiveSupport::HashWithIndifferentAccess
    would not act as alias for #symbolize_keys.

    Nick Weiland

  • Improve the logic that detects non-autoloaded constants.

    Jan Habermann, Xavier Noria

  • Fix bug where URI.unescape would fail with mixed Unicode/escaped character input:

    URI.unescape("\xe3\x83\x90")  # => "バ"
    URI.unescape("%E3%83%90")  # => "バ"
    URI.unescape("\xe3\x83\x90%E3%83%90")  # => Encoding::CompatibilityError
    

    Ashe Connor, Aaron Patterson

Active Model

  • Fix numericality validator to still use value before type cast except Active Record.

    Fixes #33651, #33686.

    Ryuta Kamizono

Active Record

  • Do not ignore the scoping with query methods in the scope block.

    Ryuta Kamizono

  • Allow aliased attributes to be used in #update_columns and #update.

    Gannon McGibbon

  • Allow spaces in postgres table names.

    Fixes issue where "user post" is misinterpreted as ""user"."post"" when quoting table names with the postgres
    adapter.

    Gannon McGibbon

  • Cached columns_hash fields should be excluded from ResultSet#column_types

    PR #34528 addresses the inconsistent behaviour when attribute is defined for an ignored column. The following test
    was passing for SQLite and MySQL, but failed for PostgreSQL:

    class DeveloperName < ActiveRecord::Type::String
      def deserialize(value)
        "Developer: #{value}"
      end
    end
    
    class AttributedDeveloper < ActiveRecord::Base
      self.table_name = "developers"
    
      attribute :name, DeveloperName.new
    
      self.ignored_columns += ["name"]
    end
    
    developer = AttributedDeveloper.create
    developer.update_column :name, "name"
    
    loaded_developer = AttributedDeveloper.where(id: developer.id).select("*").first
    puts loaded_developer.name # should be "Developer: name" but it's just "name"
    

    Dmitry Tsepelev

  • Values of enum are frozen, raising an error when attempting to modify them.

    Emmanuel Byrd

  • update_columns now correctly raises ActiveModel::MissingAttributeError
    if the attribute does not exist.

    Sean Griffin

  • Do not use prepared statement in queries that have a large number of binds.

    Ryuta Kamizono

  • Fix query cache to load before first request.

    Eileen M. Uchitelle

  • Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error.

    Fixes #33056.

    Federico Martinez

  • Fix duplicated record creation when using nested attributes with create_with.

    Darwin Wu

  • Fix regression setting children record in parent before_save callback.

    Guo Xiang Tan

  • Prevent leaking of user's DB credentials on rails db:create failure.

    bogdanvlviv

  • Clear mutation tracker before continuing the around callbacks.

    Yuya Tanaka

  • Prevent deadlocks when waiting for connection from pool.

    Brent Wheeldon

  • Avoid extra scoping when using Relation#update that was causing this method to change the current scope.

    Ryuta Kamizono

  • Fix numericality validator not to be affected by custom getter.

    Ryuta Kamizono

  • Fix bulk change table ignores comment option on PostgreSQL.

    Yoshiyuki Kinjo

Action View

  • No changes.

Action Pack

  • Reset Capybara sessions if failed system test screenshot raising an exception.

    Reset Capybara sessions if take_failed_screenshot raise exception
    in system test after_teardown.

    Maxim Perepelitsa

  • Use request object for context if there's no controller

    There is no controller instance when using a redirect route or a
    mounted rack application so pass the request object as the context
    when resolving dynamic CSP sources in this scenario.

    Fixes #34200.

    Andrew White

  • Apply mapping to symbols returned from dynamic CSP sources

    Previously if a dynamic source returned a symbol such as :self it
    would be converted to a string implicity, e.g:

    policy.default_src -> { :self }
    

    would generate the header:

    Content-Security-Policy: default-src self
    

    and now it generates:

    Content-Security-Policy: default-src 'self'
    

    Andrew White

  • Fix rails routes -c for controller name consists of multiple word.

    Yoshiyuki Kinjo

  • Call the #redirect_to block in controller context.

    Steven Peckins

Active Job

  • Make sure assert_enqueued_with() & assert_performed_with() work reliably with hash arguments.

    Sharang Dashputre

  • Restore ActionController::Parameters support to ActiveJob::Arguments.serialize.

    Bernie Chiu

  • Restore HashWithIndifferentAccess support to ActiveJob::Arguments.deserialize.

    Gannon McGibbon

  • Include deserialized arguments in job instances returned from
    assert_enqueued_with and assert_performed_with

    Alan Wu

  • Increment execution count before deserialize arguments.

    Currently, the execution count increments after deserializes arguments.
    Therefore, if an error occurs with deserialize, it retries indefinitely.

    Yuji Yaginuma

Action Mailer

  • No changes.

Action Cable

  • No changes.

Active Storage

  • Support multiple submit buttons in Active Storage forms.

    Chrıs Seelus

  • Fix ArgumentError when uploading to amazon s3

    Hiroki Sanpei

  • Add a foreign-key constraint to the active_storage_attachments table for blobs.

    George Claghorn

  • Discard ActiveStorage::PurgeJobs for missing blobs.

    George Claghorn

  • Fix uploading Tempfiles to Azure Storage.

    George Claghorn

Railties

  • Disable content security policy for mailer previews.

    Dylan Reile

  • Log the remote IP address of clients behind a proxy.

    Atul Bhosale

- Ruby
Published by rafaelfranca over 7 years ago