gems activerecord 6.0.0.beta1

latest releases: 7.1.3.2, 7.1.3.1, 7.0.8.1...
5 years ago

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

Don't miss a new activerecord release

NewReleases is sending notifications on new releases.