rails 7.2.0
Active Support
-
Fix
delegate_missing_to allow_nil: truewhen called with implict selfclass Person delegate_missing_to :address, allow_nil: true def address nil end def berliner? city == "Berlin" end end Person.new.city # => nil Person.new.berliner? # undefined local variable or method `city' for an instance of Person (NameError)Jean Boussier
-
Add
loggeras a dependency since it is a bundled gem candidate for Ruby 3.5Earlopain
-
Define
Digest::UUID.nil_uuid, which returns the so-called nil UUID.Xavier Noria
-
Support
durationtype inActiveSupport::XmlMini.heka1024
-
Remove deprecated
ActiveSupport::Notifications::Event#childrenandActiveSupport::Notifications::Event#parent_of?.Rafael Mendonça França
-
Remove deprecated support to call the following methods without passing a deprecator:
deprecatedeprecate_constantActiveSupport::Deprecation::DeprecatedObjectProxy.newActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.newActiveSupport::Deprecation::DeprecatedConstantProxy.newassert_deprecatedassert_not_deprecatedcollect_deprecations
Rafael Mendonça França
-
Remove deprecated
ActiveSupport::Deprecationdelegation to instance.Rafael Mendonça França
-
Remove deprecated
SafeBuffer#clone_empty.Rafael Mendonça França
-
Remove deprecated
#to_default_sfromArray,Date,DateTimeandTime.Rafael Mendonça França
-
Remove deprecated support to passing
Dalli::Clientinstances toMemCacheStore.Rafael Mendonça França
-
Remove deprecated
config.active_support.use_rfc4122_namespaced_uuids.Rafael Mendonça França
-
Remove deprecated
config.active_support.remove_deprecated_time_with_zone_name.Rafael Mendonça França
-
Remove deprecated
config.active_support.disable_to_s_conversion.Rafael Mendonça França
-
Remove deprecated support to bolding log text with positional boolean in
ActiveSupport::LogSubscriber#color.Rafael Mendonça França
-
Remove deprecated constants
ActiveSupport::LogSubscriber::CLEARandActiveSupport::LogSubscriber::BOLD.Rafael Mendonça França
-
Remove deprecated support for
config.active_support.cache_format_version = 6.1.Rafael Mendonça França
-
Remove deprecated
:pool_sizeand:pool_timeoutoptions for the cache storage.Rafael Mendonça França
-
Warn on tests without assertions.
ActiveSupport::TestCasenow warns when tests do not run any assertions. This is helpful in detecting broken tests that do not perform intended assertions.fatkodima
-
Support
hexBinarytype inActiveSupport::XmlMini.heka1024
-
Deprecate
ActiveSupport::ProxyObjectin favor of Ruby's built-inBasicObject.Earlopain
-
stub_constnow accepts aexists: falseparameter to allow stubbing missing constants.Jean Boussier
-
Make
ActiveSupport::BacktraceCleanercopy filters and silencers on dup and clone.Previously the copy would still share the internal silencers and filters array, causing state to leak.
Jean Boussier
-
Updating Astana with Western Kazakhstan TZInfo identifier.
Damian Nelson
-
Add filename support for
ActiveSupport::Logger.logger_outputs_to?.logger = Logger.new('/var/log/rails.log') ActiveSupport::Logger.logger_outputs_to?(logger, '/var/log/rails.log')Christian Schmidt
-
Include
IPAddr#prefixwhen serializing anIPAddrusing theActiveSupport::MessagePackserializer.This change is backward and forward compatible — old payloads can still be read, and new payloads will be readable by older versions of Rails.
Taiki Komaba
-
Add
default:support forActiveSupport::CurrentAttributes.attribute.class Current < ActiveSupport::CurrentAttributes attribute :counter, default: 0 endSean Doyle
-
Yield instance to
Object#withblock.client.with(timeout: 5_000) do |c| c.get("/commits") endSean Doyle
-
Use logical core count instead of physical core count to determine the default number of workers when parallelizing tests.
Jonathan Hefner
-
Fix
Time.now/DateTime.now/Date.todayto return results in a system timezone after#travel_to.There is a bug in the current implementation of #travel_to: it remembers a timezone of its argument, and all stubbed methods start returning results in that remembered timezone. However, the expected behavior is to return results in a system timezone.
Aleksei Chernenkov
-
Add
ErrorReported#unexpectedto report precondition violations.For example:
def edit if published? Rails.error.unexpected("[BUG] Attempting to edit a published article, that shouldn't be possible") return false end # ... endThe above will raise an error in development and test, but only report the error in production.
Jean Boussier
-
Make the order of read_multi and write_multi notifications for
Cache::Store#fetch_multioperations match the order they are executed in.Adam Renberg Tamm
-
Make return values of
Cache::Store#writeconsistent.The return value was not specified before. Now it returns
trueon a successful write,nilif there was an error talking to the cache backend, andfalseif the write failed for another reason (e.g. the key already exists andunless_exist: truewas passed).Sander Verdonschot
-
Fix logged cache keys not always matching actual key used by cache action.
Hartley McGuire
-
Improve error messages of
assert_changesandassert_no_changes.assert_changeserror messages now display objects with.inspectto make it easier to differentiate nil from empty strings, strings from symbols, etc.assert_no_changeserror messages now surface the actual value.pcreux
-
Fix
#to_fs(:human_size)to correctly work with negative numbers.Earlopain
-
Fix
BroadcastLogger#dupso that it duplicates the logger'sbroadcasts.Andrew Novoselac
-
Fix issue where
bootstrap.rboverwrites thelevelof aBroadcastLogger'sbroadcasts.Andrew Novoselac
-
Fix compatibility with the
semantic_loggergem.The
semantic_loggergem doesn't behave exactly like stdlib logger in thatSemanticLogger#levelreturns a Symbol while stdlibLogger#levelreturns an Integer.This caused the various
LogSubscriberclasses in Rails to break when assigned aSemanticLoggerinstance.Jean Boussier, ojab
-
Fix MemoryStore to prevent race conditions when incrementing or decrementing.
Pierre Jambet
-
Implement
HashWithIndifferentAccess#to_proc.Previously, calling
#to_proconHashWithIndifferentAccessobject used inherited#to_procmethod from theHashclass, which was not able to access values using indifferent keys.fatkodima
Active Model
-
Fix a bug where type casting of string to
TimeandDateTimedoesn't calculate minus minute value in TZ offset correctly.Akira Matsuda
-
Port the
type_for_attributemethod to Active Model. Classes that includeActiveModel::Attributeswill now provide this method. This method behaves the same for Active Model as it does for Active Record.class MyModel include ActiveModel::Attributes attribute :my_attribute, :integer end MyModel.type_for_attribute(:my_attribute) # => #<ActiveModel::Type::Integer ...>Jonathan Hefner
Active Record
-
Handle commas in Sqlite3 default function definitions.
Stephen Margheim
-
Fixes
validates_associatedraising an exception when configured with a singular association and havingindex_nested_attribute_errorsenabled.Martin Spickermann
-
The constant
ActiveRecord::ImmutableRelationhas been deprecated because we want to reserve that name for a stronger sense of "immutable relation". Please useActiveRecord::UnmodifiableRelationinstead.Xavier Noria
-
Add condensed
#inspectforConnectionPool,AbstractAdapter, andDatabaseConfig.Hartley McGuire
-
Fixed a memory performance issue in Active Record attribute methods definition.
Jean Boussier
-
Define the new Active Support notification event
start_transaction.active_record.This event is fired when database transactions or savepoints start, and complements
transaction.active_record, which is emitted when they finish.The payload has the transaction (
:transaction) and the connection (:connection).Xavier Noria
-
Fix an issue where the IDs reader method did not return expected results for preloaded associations in models using composite primary keys.
Jay Ang
-
The payload of
sql.active_recordActive Support notifications now has the current transaction in the:transactionkey.Xavier Noria
-
The payload of
transaction.active_recordActive Support notifications now has the transaction the event is related to in the:transactionkey.Xavier Noria
-
Define
ActiveRecord::Transaction#uuid, which returns a UUID for the database transaction. This may be helpful when tracing database activity. These UUIDs are generated only on demand.Xavier Noria
-
Fix inference of association model on nested models with the same demodularized name.
E.g. with the following setup:
class Nested::Post < ApplicationRecord has_one :post, through: :other endBefore,
#postwould infer the model asNested::Post, but now it correctly infersPost.Joshua Young
-
PostgreSQL
Cidr#change?detects the address prefix change.Taketo Takashima
-
Change
BatchEnumerator#destroy_allto return the total number of affected rows.Previously, it always returned
nil.fatkodima
-
Support
touch_allin batches.Post.in_batches.touch_allfatkodima
-
Add support for
:if_not_existsand:forceoptions tocreate_schema.fatkodima
-
Fix
index_errorshaving incorrect index in association validation errors.lulalala
-
Add
index_errors: :nested_attributes_ordermode.This indexes the association validation errors based on the order received by nested attributes setter, and respects the
reject_ifconfiguration. This enables API to provide enough information to the frontend to map the validation errors back to their respective form fields.lulalala
-
Add
Rails.application.config.active_record.postgresql_adapter_decode_datesto opt out of decoding dates automatically with the postgresql adapter. Defaults to true.Joé Dupuis
-
Association option
query_constraintsis deprecated in favor offoreign_key.Nikita Vasilevsky
-
Add
ENV["SKIP_TEST_DATABASE_TRUNCATE"]flag to speed up multi-process test runs on large DBs when all tests run within default transaction.This cuts ~10s from the test run of HEY when run by 24 processes against the 178 tables, since ~4,000 table truncates can then be skipped.
DHH
-
Added support for recursive common table expressions.
Post.with_recursive( post_and_replies: [ Post.where(id: 42), Post.joins('JOIN post_and_replies ON posts.in_reply_to_id = post_and_replies.id'), ] )Generates the following SQL:
WITH RECURSIVE "post_and_replies" AS ( (SELECT "posts".* FROM "posts" WHERE "posts"."id" = 42) UNION ALL (SELECT "posts".* FROM "posts" JOIN post_and_replies ON posts.in_reply_to_id = post_and_replies.id) ) SELECT "posts".* FROM "posts"ClearlyClaire
-
validate_constraintcan be called in achange_tableblock.ex:
change_table :products do |t| t.check_constraint "price > discounted_price", name: "price_check", validate: false t.validate_check_constraint "price_check" endCody Cutrer
-
PostgreSQLAdapternow decodes columns of type date toDateinstead of string.Ex:
ActiveRecord::Base.connection .select_value("select '2024-01-01'::date").class #=> DateJoé Dupuis
-
Strict loading using
:n_plus_one_onlydoes not eagerly load child associations.With this change, child associations are no longer eagerly loaded, to match intended behavior and to prevent non-deterministic order issues caused by calling methods like
firstorlast. Asfirstandlastdon't cause an N+1 by themselves, calling child associations will no longer raise. Fixes #49473.Before:
person = Person.find(1) person.strict_loading!(mode: :n_plus_one_only) person.posts.first # SELECT * FROM posts WHERE person_id = 1; -- non-deterministic order person.posts.first.firm # raises ActiveRecord::StrictLoadingViolationErrorAfter:
person = Person.find(1) person.strict_loading!(mode: :n_plus_one_only) person.posts.first # this is 1+1, not N+1 # SELECT * FROM posts WHERE person_id = 1 ORDER BY id LIMIT 1; person.posts.first.firm # no longer raisesReid Lynch
-
Allow
Sqlite3Adapterto usesqlite3gem version2.x.Mike Dalessio
-
Allow
ActiveRecord::Base#pluckto accept hash values.# Before Post.joins(:comments).pluck("posts.id", "comments.id", "comments.body") # After Post.joins(:comments).pluck(posts: [:id], comments: [:id, :body])fatkodima
-
Raise an
ActiveRecord::ActiveRecordErrorerror when the MySQL database returns an invalid version string.Kevin McPhillips
-
ActiveRecord::Base.transactionnow yields anActiveRecord::Transactionobject.This allows to register callbacks on it.
Article.transaction do |transaction| article.update(published: true) transaction.after_commit do PublishNotificationMailer.with(article: article).deliver_later end endJean Boussier
-
Add
ActiveRecord::Base.current_transaction.Returns the current transaction, to allow registering callbacks on it.
Article.current_transaction.after_commit do PublishNotificationMailer.with(article: article).deliver_later endJean Boussier
-
Add
ActiveRecord.after_all_transactions_commitcallback.Useful for code that may run either inside or outside a transaction and needs to perform work after the state changes have been properly persisted.
def publish_article(article) article.update(published: true) ActiveRecord.after_all_transactions_commit do PublishNotificationMailer.with(article: article).deliver_later end endIn the above example, the block is either executed immediately if called outside of a transaction, or called after the open transaction is committed.
If the transaction is rolled back, the block isn't called.
Jean Boussier
-
Add the ability to ignore counter cache columns until they are backfilled.
Starting to use counter caches on existing large tables can be troublesome, because the column values must be backfilled separately of the column addition (to not lock the table for too long) and before the use of
:counter_cache(otherwise methods likesize/any?/etc, which use counter caches internally, can produce incorrect results). People usually use database triggers or callbacks on child associations while backfilling before introducing a counter cache configuration to the association.Now, to safely backfill the column, while keeping the column updated with child records added/removed, use:
class Comment < ApplicationRecord belongs_to :post, counter_cache: { active: false } endWhile the counter cache is not "active", the methods like
size/any?/etc will not use it, but get the results directly from the database. After the counter cache column is backfilled, simply remove the{ active: false }part from the counter cache definition, and it will now be used by the mentioned methods.fatkodima
-
Retry known idempotent SELECT queries on connection-related exceptions.
SELECT queries we construct by walking the Arel tree and / or with known model attributes are idempotent and can safely be retried in the case of a connection error. Previously, adapters such as
TrilogyAdapterwould raiseActiveRecord::ConnectionFailed: Trilogy::EOFErrorwhen encountering a connection error mid-request.Adrianna Chang
-
Allow association's
foreign_keyto be composite.query_constraintsoption was the only way to configure a composite foreign key by passing anArray. Now it's possible to pass an Array value asforeign_keyto achieve the same behavior of an association.Nikita Vasilevsky
-
Allow association's
primary_keyto be composite.Association's
primary_keycan be composite when derived from associated modelprimary_keyorquery_constraints. Now it's possible to explicitly set it as composite on the association.Nikita Vasilevsky
-
Add
config.active_record.permanent_connection_checkoutsetting.Controls whether
ActiveRecord::Base.connectionraises an error, emits a deprecation warning, or neither.ActiveRecord::Base.connectioncheckouts a database connection from the pool and keeps it leased until the end of the request or job. This behavior can be undesirable in environments that use many more threads or fibers than there is available connections.This configuration can be used to track down and eliminate code that calls
ActiveRecord::Base.connectionand migrate it to useActiveRecord::Base.with_connectioninstead.The default behavior remains unchanged, and there is currently no plans to change the default.
Jean Boussier
-
Add dirties option to uncached.
This adds a
dirtiesoption toActiveRecord::Base.uncachedandActiveRecord::ConnectionAdapters::ConnectionPool#uncached.When set to
true(the default), writes will clear all query caches belonging to the current thread. When set tofalse, writes to the affected connection pool will not clear any query cache.This is needed by Solid Cache so that cache writes do not clear query caches.
Donal McBreen
-
Deprecate
ActiveRecord::Base.connectionin favor of.lease_connection.The method has been renamed as
lease_connectionto better reflect that the returned connection will be held for the duration of the request or job.This deprecation is a soft deprecation, no warnings will be issued and there is no current plan to remove the method.
Jean Boussier
-
Deprecate
ActiveRecord::ConnectionAdapters::ConnectionPool#connection.The method has been renamed as
lease_connectionto better reflect that the returned connection will be held for the duration of the request or job.Jean Boussier
-
Expose a generic fixture accessor for fixture names that may conflict with Minitest.
assert_equal "Ruby on Rails", web_sites(:rubyonrails).name assert_equal "Ruby on Rails", fixture(:web_sites, :rubyonrails).nameJean Boussier
-
Using
Model.query_constraintswith a single non-primary-key column used to raise as expected, but with an incorrect error message.This has been fixed to raise with a more appropriate error message.
Joshua Young
-
Fix
has_oneassociation autosave setting the foreign key attribute when it is unchanged.This behavior is also inconsistent with autosaving
belongs_toand can have unintended side effects like raising anActiveRecord::ReadonlyAttributeErrorwhen the foreign key attribute is marked as read-only.Joshua Young
-
Remove deprecated behavior that would rollback a transaction block when exited using
return,breakorthrow.Rafael Mendonça França
-
Deprecate
Rails.application.config.active_record.commit_transaction_on_non_local_return.Rafael Mendonça França
-
Remove deprecated support to pass
rewheretoActiveRecord::Relation#merge.Rafael Mendonça França
-
Remove deprecated support to pass
deferrable: truetoadd_foreign_key.Rafael Mendonça França
-
Remove deprecated support to quote
ActiveSupport::Duration.Rafael Mendonça França
-
Remove deprecated
#quote_bound_value.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::ConnectionAdapters::ConnectionPool#connection_klass.Rafael Mendonça França
-
Remove deprecated support to apply
#connection_pool_list,#active_connections?,#clear_active_connections!,#clear_reloadable_connections!,#clear_all_connections!and#flush_idle_connections!to the connections pools for the current role when theroleargument isn't provided.Rafael Mendonça França
-
Remove deprecated
#all_connection_pools.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::ConnectionAdapters::SchemaCache#data_sources.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::ConnectionAdapters::SchemaCache.load_from.Rafael Mendonça França
-
Remove deprecated
#all_foreign_keys_valid?from database adapters.Rafael Mendonça França
-
Remove deprecated support to passing coder and class as second argument to
serialize.Rafael Mendonça França
-
Remove deprecated support to
ActiveRecord::Base#read_attribute(:id)to return the custom primary key value.Rafael Mendonça França
-
Remove deprecated
TestFixtures.fixture_path.Rafael Mendonça França
-
Remove deprecated behavior to support referring to a singular association by its plural name.
Rafael Mendonça França
-
Deprecate
Rails.application.config.active_record.allow_deprecated_singular_associations_name.Rafael Mendonça França
-
Remove deprecated support to passing
SchemaMigrationandInternalMetadataclasses as arguments toActiveRecord::MigrationContext.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Migration.check_pending!method.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::LogSubscriber.runtimemethod.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::LogSubscriber.runtime=method.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::LogSubscriber.reset_runtimemethod.Rafael Mendonça França
-
Remove deprecated support to define
explainin the connection adapter with 2 arguments.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::ActiveJobRequiredError.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base.clear_active_connections!.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base.clear_reloadable_connections!.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base.clear_all_connections!.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base.flush_idle_connections!.Rafael Mendonça França
-
Remove deprecated
nameargument fromActiveRecord::Base.remove_connection.Rafael Mendonça França
-
Remove deprecated support to call
alias_attributewith non-existent attribute names.Rafael Mendonça França
-
Remove deprecated
Rails.application.config.active_record.suppress_multiple_database_warning.Rafael Mendonça França
-
Add
ActiveRecord::Encryption::MessagePackMessageSerializer.Serialize data to the MessagePack format, for efficient storage in binary columns.
The binary encoding requires around 30% less space than the base64 encoding used by the default serializer.
Donal McBreen
-
Add support for encrypting binary columns.
Ensure encryption and decryption pass
Type::Binary::Dataaround for binary data.Previously encrypting binary columns with the
ActiveRecord::Encryption::MessageSerializerincidentally worked for MySQL and SQLite, but not PostgreSQL.Donal McBreen
-
Deprecated
ENV["SCHEMA_CACHE"]in favor ofschema_cache_pathin the database configuration.Rafael Mendonça França
-
Add
ActiveRecord::Base.with_connectionas a shortcut for leasing a connection for a short duration.The leased connection is yielded, and for the duration of the block, any call to
ActiveRecord::Base.connectionwill yield that same connection.This is useful to perform a few database operations without causing a connection to be leased for the entire duration of the request or job.
Jean Boussier
-
Deprecate
config.active_record.warn_on_records_fetched_greater_thannow thatsql.active_recordnotification includes:row_countfield.Jason Nochlin
-
The fix ensures that the association is joined using the appropriate join type (either inner join or left outer join) based on the existing joins in the scope.
This prevents unintentional overrides of existing join types and ensures consistency in the generated SQL queries.
Example:
# `associated` will use `LEFT JOIN` instead of using `JOIN` Post.left_joins(:author).where.associated(:author)Saleh Alhaddad
-
Fix an issue where
ActiveRecord::Encryptionconfigurations are not ready before the loading of Active Record models, when an application is eager loaded. As a result, encrypted attributes could be misconfigured in some cases.Maxime Réty
-
Deprecate defining an
enumwith keyword arguments.class Function > ApplicationRecord # BAD enum color: [:red, :blue], type: [:instance, :class] # GOOD enum :color, [:red, :blue] enum :type, [:instance, :class] endHartley McGuire
-
Add
config.active_record.validate_migration_timestampsoption for validating migration timestamps.When set, validates that the timestamp prefix for a migration is no more than a day ahead of the timestamp associated with the current time. This is designed to prevent migrations prefixes from being hand-edited to future timestamps, which impacts migration generation and other migration commands.
Adrianna Chang
-
Properly synchronize
Mysql2Adapter#active?andTrilogyAdapter#active?.As well as
disconnect!andverify!.This generally isn't a big problem as connections must not be shared between threads, but is required when running transactional tests or system tests and could lead to a SEGV.
Jean Boussier
-
Support
:source_locationtag option for query log tags.config.active_record.query_log_tags << :source_locationCalculating the caller location is a costly operation and should be used primarily in development (note, there is also a
config.active_record.verbose_query_logsthat serves the same purpose) or occasionally on production for debugging purposes.fatkodima
-
Add an option to
ActiveRecord::Encryption::Encryptorto disable compression.Allow compression to be disabled by setting
compress: falseclass User encrypts :name, encryptor: ActiveRecord::Encryption::Encryptor.new(compress: false) endDonal McBreen
-
Deprecate passing strings to
ActiveRecord::Tasks::DatabaseTasks.cache_dump_filename.A
ActiveRecord::DatabaseConfigurations::DatabaseConfigobject should be passed instead.Rafael Mendonça França
-
Add
row_countfield tosql.active_recordnotification.This field returns the amount of rows returned by the query that emitted the notification.
This metric is useful in cases where one wants to detect queries with big result sets.
Marvin Bitterlich
-
Consistently raise an
ArgumentErrorwhen passing an invalid argument to a nested attributes association writer.Previously, this would only raise on collection associations and produce a generic error on singular associations.
Now, it will raise on both collection and singular associations.
Joshua Young
-
Fix single quote escapes on default generated MySQL columns.
MySQL 5.7.5+ supports generated columns, which can be used to create a column that is computed from an expression.
Previously, the schema dump would output a string with double escapes for generated columns with single quotes in the default expression.
This would result in issues when importing the schema on a fresh instance of a MySQL database.
Now, the string will not be escaped and will be valid Ruby upon importing of the schema.
Yash Kapadia
-
Fix Migrations with versions older than 7.1 validating options given to
add_referenceandt.references.Hartley McGuire
-
Add
<role>_typesclass method toActiveRecord::DelegatedTypeso that the delegated types can be introspected.JP Rosevear
-
Make
schema_dump,query_cache,replicaanddatabase_tasksconfigurable viaDATABASE_URL.This wouldn't always work previously because boolean values would be interpreted as strings.
e.g.
DATABASE_URL=postgres://localhost/foo?schema_dump=falsenow properly disable dumping the schema cache.Mike Coutermarsh, Jean Boussier
-
Introduce
ActiveRecord::Transactions::ClassMethods#set_callback.It is identical to
ActiveSupport::Callbacks::ClassMethods#set_callbackbut with support forafter_commitandafter_rollbackcallback options.Joshua Young
-
Make
ActiveRecord::Encryption::Encryptoragnostic of the serialization format used for encrypted data.Previously, the encryptor instance only allowed an encrypted value serialized as a
Stringto be passed to the message serializer.Now, the encryptor lets the configured
message_serializerdecide which types of serialized encrypted values are supported. A custom serialiser is therefore allowed to serializeActiveRecord::Encryption::Messageobjects using a type other thanString.The default
ActiveRecord::Encryption::MessageSerializeralready ensures that onlyStringobjects are passed for deserialization.Maxime Réty
-
Fix
encrypted_attribute?to take into account context properties passed toencrypts.Maxime Réty
-
The object returned by
explainnow responds topluck,first,last,average,count,maximum,minimum, andsum. Those new methods runEXPLAINon the corresponding queries:User.all.explain.count # EXPLAIN SELECT COUNT(*) FROM `users` # ... User.all.explain.maximum(:id) # EXPLAIN SELECT MAX(`users`.`id`) FROM `users` # ...Petrik de Heus
-
Fixes an issue where
validates_associated:onoption wasn't respected when validating associated records.Austen Madden, Alex Ghiculescu, Rafał Brize
-
Allow overriding SQLite defaults from
database.yml.Any PRAGMA configuration set under the
pragmaskey in the configuration file takes precedence over Rails' defaults, and additional PRAGMAs can be set as well.database: storage/development.sqlite3 timeout: 5000 pragmas: journal_mode: off temp_store: memoryStephen Margheim
-
Remove warning message when running SQLite in production, but leave it unconfigured.
There are valid use cases for running SQLite in production. However, it must be done with care, so instead of a warning most users won't see anyway, it's preferable to leave the configuration commented out to force them to think about having the database on a persistent volume etc.
Jacopo Beschi, Jean Boussier
-
Add support for generated columns to the SQLite3 adapter.
Generated columns (both stored and dynamic) are supported since version 3.31.0 of SQLite. This adds support for those to the SQLite3 adapter.
create_table :users do |t| t.string :name t.virtual :name_upper, type: :string, as: 'UPPER(name)' t.virtual :name_lower, type: :string, as: 'LOWER(name)', stored: true endStephen Margheim
-
TrilogyAdapter: ignore
hostifsocketparameter is set.This allows to configure a connection on a UNIX socket via
DATABASE_URL:DATABASE_URL=trilogy://does-not-matter/my_db_production?socket=/var/run/mysql.sockJean Boussier
-
Make
assert_queries_count,assert_no_queries,assert_queries_match, andassert_no_queries_matchassertions public.To assert the expected number of queries are made, Rails internally uses
assert_queries_countandassert_no_queries. To assert that specific SQL queries are made,assert_queries_matchandassert_no_queries_matchare used. These assertions can now be used in applications as well.class ArticleTest < ActiveSupport::TestCase test "queries are made" do assert_queries_count(1) { Article.first } end test "creates a foreign key" do assert_queries_match(/ADD FOREIGN KEY/i, include_schema: true) do @connection.add_foreign_key(:comments, :posts) end end endPetrik de Heus, fatkodima
-
Fix
has_secure_tokencalls the setter method on initialize.Abeid Ahmed
-
When using a
DATABASE_URL, allow for a configuration to map the protocol in the URL to a specific database adapter. This allows decoupling the adapter the application chooses to use from the database connection details set in the deployment environment.# ENV['DATABASE_URL'] = "mysql://localhost/example_database" config.active_record.protocol_adapters.mysql = "trilogy" # will connect to MySQL using the trilogy adapterJean Boussier, Kevin McPhillips
-
In cases where MySQL returns
warning_countgreater than zero, but returns no warnings when theSHOW WARNINGSquery is executed,ActiveRecord.db_warnings_actionproc will still be called with a generic warning message rather than silently ignoring the warning(s).Kevin McPhillips
-
DatabaseConfigurations#configs_foraccepts a symbol in thenameparameter.Andrew Novoselac
-
Fix
where(field: values)queries whenfieldis a serialized attribute (for example, whenfieldusesActiveRecord::Base.serializeor is a JSON column).João Alves
-
Make the output of
ActiveRecord::Core#inspectconfigurable.By default, calling
inspecton a record will yield a formatted string including just theid.Post.first.inspect #=> "#<Post id: 1>"The attributes to be included in the output of
inspectcan be configured withActiveRecord::Core#attributes_for_inspect.Post.attributes_for_inspect = [:id, :title] Post.first.inspect #=> "#<Post id: 1, title: "Hello, World!">"With
attributes_for_inspectset to:all,inspectwill list all the record's attributes.Post.attributes_for_inspect = :all Post.first.inspect #=> "#<Post id: 1, title: "Hello, World!", published_at: "2023-10-23 14:28:11 +0000">"In
developmentandtestmode,attributes_for_inspectwill be set to:allby default.You can also call
full_inspectto get an inspection with all the attributes.The attributes in
attribute_for_inspectwill also be used forpretty_print.Andrew Novoselac
-
Don't mark attributes as changed when reassigned to
Float::INFINITYor-Float::INFINITY.Maicol Bentancor
-
Support the
RETURNINGclause for MariaDB.fatkodima, Nikolay Kondratyev
-
The SQLite3 adapter now implements the
supports_deferrable_constraints?contract.Allows foreign keys to be deferred by adding the
:deferrablekey to theforeign_keyoptions.add_reference :person, :alias, foreign_key: { deferrable: :deferred } add_reference :alias, :person, foreign_key: { deferrable: :deferred }Stephen Margheim
-
Add the
set_constraintshelper to PostgreSQL connections.Post.create!(user_id: -1) # => ActiveRecord::InvalidForeignKey Post.transaction do Post.connection.set_constraints(:deferred) p = Post.create!(user_id: -1) u = User.create! p.user = u p.save! endCody Cutrer
-
Include
ActiveModel::APIinActiveRecord::Base.Sean Doyle
-
Ensure
#signed_idoutputsurl_safestrings.Jason Meller
-
Add
nulls_lastand workingdesc.nulls_firstfor MySQL.Tristan Fellows
-
Allow for more complex hash arguments for
orderwhich mimicswhereinActiveRecord::Relation.Topic.includes(:posts).order(posts: { created_at: :desc })Myles Boone
Action View
-
Fix templates with strict locals to also include
local_assigns.Previously templates defining strict locals wouldn't receive the
local_assignshash.Jean Boussier
-
Add queries count to template rendering instrumentation.
# Before Completed 200 OK in 3804ms (Views: 41.0ms | ActiveRecord: 33.5ms | Allocations: 112788) # After Completed 200 OK in 3804ms (Views: 41.0ms | ActiveRecord: 33.5ms (2 queries, 1 cached) | Allocations: 112788)fatkodima
-
Raise
ArgumentErrorif:renderableobject does not respond to#render_in.Sean Doyle
-
Add the
nonce: trueoption forstylesheet_link_taghelper to support automatic nonce generation for Content Security Policy.Works the same way as
javascript_include_tag nonce: truedoes.Akhil G Krishnan, AJ Esler
-
Parse
ActionView::TestCase#renderedHTML content asNokogiri::XML::DocumentFragmentinstead ofNokogiri::XML::Document.Sean Doyle
-
Rename
ActionView::TestCase::Behavior::ContenttoActionView::TestCase::Behavior::RenderedViewContent.Make
RenderedViewContentinherit fromString. Make private API with:nodoc:Sean Doyle
-
Deprecate passing
nilas value for themodel:argument to theform_withmethod.Collin Jilbert
-
Alias
field_set_taghelper tofieldset_tagto match<fieldset>element.Sean Doyle
-
Deprecate passing content to void elements when using
tag.brtype tag builders.Hartley McGuire
-
Fix the
number_to_human_sizeview helper to correctly work with negative numbers.Earlopain
-
Automatically discard the implicit locals injected by collection rendering for template that can't accept them.
When rendering a collection, two implicit variables are injected, which breaks templates with strict locals.
Now they are only passed if the template will actually accept them.
Yasha Krasnou, Jean Boussier
-
Fix
@rails/ujscallingstart()an extra time when using bundlers.Hartley McGuire, Ryunosuke Sato
-
Fix the
captureview helper compatibility with HAML and Slim.When a blank string was captured in HAML or Slim (and possibly other template engines) it would instead return the entire buffer.
Jean Boussier
-
Updated
@rails/ujsfiles to ignore certain data-* attributes when element is contenteditable.This fix was already landed in >= 7.0.4.3, < 7.1.0. [CVE-2023-23913]
Ryunosuke Sato
-
Added validation for HTML tag names in the
tagandcontent_taghelper method.The
tagandcontent_tagmethod now checks that the provided tag name adheres to the HTML specification. If an invalid HTML tag name is provided, the method raises anArgumentErrorwith an appropriate error message.Examples:
# Raises ArgumentError: Invalid HTML5 tag name: 12p content_tag("12p") # Starting with a number # Raises ArgumentError: Invalid HTML5 tag name: "" content_tag("") # Empty tag name # Raises ArgumentError: Invalid HTML5 tag name: div/ tag("div/") # Contains a solidus # Raises ArgumentError: Invalid HTML5 tag name: "image file" tag("image file") # Contains a spaceAkhil G Krishnan
Action Pack
-
Allow bots to ignore
allow_browser.Matthew Nguyen
-
Include the HTTP Permissions-Policy on non-HTML Content-Types [CVE-2024-28103]
Aaron Patterson, Zack Deveau
-
Fix
Mime::Type.parsehandling type parameters for HTTP Accept headers.Taylor Chaparro
-
Fix the error page that is displayed when a view template is missing to account for nested controller paths in the suggested correct location for the missing template.
Joshua Young
-
Add
save_and_open_pagehelper toIntegrationTest.save_and_open_pageis a helpful helper to keep a short feedback loop when working on system tests. A similar helper with matching signature has been added to integration tests.Joé Dupuis
-
Fix a regression in 7.1.3 passing a
to:option without a controller when the controller is already defined by a scope.Rails.application.routes.draw do controller :home do get "recent", to: "recent_posts" end endÉtienne Barrié
-
Request Forgery takes relative paths into account.
Stefan Wienert
-
Add ".test" as a default allowed host in development to ensure smooth golden-path setup with puma.dev.
DHH
-
Add
allow_browserto set minimum browser versions for the application.A browser that's blocked will by default be served the file in
public/406-unsupported-browser.htmlwith a HTTP status code of "406 Not Acceptable".class ApplicationController < ActionController::Base # Allow only browsers natively supporting webp images, web push, badges, import maps, CSS nesting + :has allow_browser versions: :modern end class ApplicationController < ActionController::Base # All versions of Chrome and Opera will be allowed, but no versions of "internet explorer" (ie). Safari needs to be 16.4+ and Firefox 121+. allow_browser versions: { safari: 16.4, firefox: 121, ie: false } end class MessagesController < ApplicationController # In addition to the browsers blocked by ApplicationController, also block Opera below 104 and Chrome below 119 for the show action. allow_browser versions: { opera: 104, chrome: 119 }, only: :show endDHH
-
Add rate limiting API.
class SessionsController < ApplicationController rate_limit to: 10, within: 3.minutes, only: :create end class SignupsController < ApplicationController rate_limit to: 1000, within: 10.seconds, by: -> { request.domain }, with: -> { redirect_to busy_controller_url, alert: "Too many signups!" }, only: :new endDHH, Jean Boussier
-
Add
image/svg+xmlto the compressible content types ofActionDispatch::Static.Georg Ledermann
-
Add instrumentation for
ActionController::Live#send_stream.Allows subscribing to
send_streamevents. The event payload contains the filename, disposition, and type.Hannah Ramadan
-
Add support for
with_routingtest helper inActionDispatch::IntegrationTest.Gannon McGibbon
-
Remove deprecated support to set
Rails.application.config.action_dispatch.show_exceptionstotrueandfalse.Rafael Mendonça França
-
Remove deprecated
speaker,vibrate, andvrpermissions policy directives.Rafael Mendonça França
-
Remove deprecated
Rails.application.config.action_dispatch.return_only_request_media_type_on_content_type.Rafael Mendonça França
-
Deprecate
Rails.application.config.action_controller.allow_deprecated_parameters_hash_equality.Rafael Mendonça França
-
Remove deprecated comparison between
ActionController::ParametersandHash.Rafael Mendonça França
-
Remove deprecated constant
AbstractController::Helpers::MissingHelperError.Rafael Mendonça França
-
Fix a race condition that could cause a
Text file busy - chromedrivererror with parallel system tests.Matt Brictson
-
Add
raccas a dependency since it will become a bundled gem in Ruby 3.4.0Hartley McGuire
-
Remove deprecated constant
ActionDispatch::IllegalStateError.Rafael Mendonça França
-
Add parameter filter capability for redirect locations.
It uses the
config.filter_parametersto match what needs to be filtered. The result would be like this:Redirected to http://secret.foo.bar?username=roque&password=[FILTERED]Fixes #14055.
Roque Pinel, Trevor Turk, tonytonyjan
Active Job
-
All tests now respect the
active_job.queue_adapterconfig.Previously if you had set
config.active_job.queue_adapterin yourconfig/application.rborconfig/environments/test.rbfile, the adapter you selected was previously not used consistently across all tests. In some tests your adapter would be used, but other tests would use theTestAdapter.In Rails 7.2, all tests will respect the
queue_adapterconfig if provided. If no config is provided, theTestAdapterwill continue to be used.See #48585 for more details.
Alex Ghiculescu
-
Make Active Job transaction aware when used conjointly with Active Record.
A common mistake with Active Job is to enqueue jobs from inside a transaction, causing them to potentially be picked and ran by another process, before the transaction is committed, which may result in various errors.
Topic.transaction do topic = Topic.create(...) NewTopicNotificationJob.perform_later(topic) endNow Active Job will automatically defer the enqueuing to after the transaction is committed, and drop the job if the transaction is rolled back.
Various queue implementations can choose to disable this behavior, and users can disable it, or force it on a per job basis:
class NewTopicNotificationJob < ApplicationJob self.enqueue_after_transaction_commit = :never # or `:always` or `:default` endJean Boussier, Cristian Bica
-
Do not trigger immediate loading of
ActiveJob::Basewhen loadingActiveJob::TestHelper.Maxime Réty
-
Preserve the serialized timezone when deserializing
ActiveSupport::TimeWithZonearguments.Joshua Young
-
Remove deprecated
:exponentially_longervalue for the:waitinretry_on.Rafael Mendonça França
-
Remove deprecated support to set numeric values to
scheduled_atattribute.Rafael Mendonça França
-
Deprecate
Rails.application.config.active_job.use_big_decimal_serialize.Rafael Mendonça França
-
Remove deprecated primitive serializer for
BigDecimalarguments.Rafael Mendonça França
Action Mailer
-
Remove deprecated params via
:argsforassert_enqueued_email_with.Rafael Mendonça França
-
Remove deprecated
config.action_mailer.preview_path.Rafael Mendonça França
Action Cable
-
Bring
ActionCable::Connection::TestCookieJarin alignment withActionDispatch::Cookies::CookieJarin regards to setting the cookie value.Before:
cookies[:foo] = { value: "bar" } puts cookies[:foo] # => { value: "bar" }After:
cookies[:foo] = { value: "bar" } puts cookies[:foo] # => "bar"Justin Ko
-
Record ping on every Action Cable message.
Previously only
pingandwelcomemessage types were keeping the connection active. Now every Action Cable message updates thepingedAtvalue, preventing the connection from being marked as stale.yauhenininjia
-
Add two new assertion methods for Action Cable test cases:
assert_has_no_streamandassert_has_no_stream_for.These methods can be used to assert that a stream has been stopped, e.g. via
stop_streamorstop_stream_for. They complement the already existingassert_has_streamandassert_has_stream_formethods.assert_has_no_stream "messages" assert_has_no_stream_for User.find(42)Sebastian Pöll, Junichi Sato
Active Storage
-
Remove deprecated
config.active_storage.silence_invalid_content_types_warning.Rafael Mendonça França
-
Remove deprecated
config.active_storage.replace_on_assign_to_many.Rafael Mendonça França
-
Add support for custom
keyinActiveStorage::Blob#compose.Elvin Efendiev
-
Add
image/webptoconfig.active_storage.web_image_content_typeswhenload_defaults "7.2"is set.Lewis Buckley
-
Fix JSON-encoding of
ActiveStorage::Filenameinstances.Jonathan del Strother
-
Fix N+1 query when fetching preview images for non-image assets.
Aaron Patterson & Justin Searls
-
Fix all Active Storage database related models to respect
ActiveRecord::Base.table_name_prefixconfiguration.Chedli Bourguiba
-
Fix
ActiveStorage::Representations::ProxyControllernot returning the proper preview image variant for previewable files.Chedli Bourguiba
-
Fix
ActiveStorage::Representations::ProxyControllerto proxy untracked variants.Chedli Bourguiba
-
When using the
preprocessed: trueoption, avoid enqueuing transform jobs for blobs that are not representable.Chedli Bourguiba
-
Prevent
ActiveStorage::Blob#previewto generate a variant if an empty variation is passed.Calls to
#url,#keyor#downloadwill now use the original preview image instead of generating a variant with the exact same dimensions.Chedli Bourguiba
-
Process preview image variant when calling
ActiveStorage::Preview#processed.For example,
attached_pdf.preview(:thumb).processedwill now immediately generate the full-sized preview image and the:thumbvariant of it. Previously, the:thumbvariant would not be generated until a further call to e.g.processed.url.Chedli Bourguiba and Jonathan Hefner
-
Prevent
ActiveRecord::StrictLoadingViolationErrorwhen strict loading is enabled and the variant of an Active Storage preview has already been processed (for example, by callingActiveStorage::Preview#url).Jonathan Hefner
-
Fix
preprocessed: trueoption for named variants of previewable files.Nico Wenterodt
-
Allow accepting
serviceas a proc as well inhas_one_attachedandhas_many_attached.Yogesh Khater
Action Mailbox
-
Fix all Action Mailbox database related models to respect
ActiveRecord::Base.table_name_prefixconfiguration.Chedli Bourguiba
Action Text
-
Only sanitize
contentattribute when present in attachments.Petrik de Heus
-
Sanitize ActionText HTML ContentAttachment in Trix edit view [CVE-2024-32464]
Aaron Patterson, Zack Deveau
-
Use
includesinstead ofeager_loadforwith_all_rich_text.Petrik de Heus
-
Delegate
ActionText::Content#deconstructtoNokogiri::XML::DocumentFragment#elements.content = ActionText::Content.new <<~HTML <h1>Hello, world</h1> <div>The body</div> HTML content => [h1, div] assert_pattern { h1 => { content: "Hello, world" } } assert_pattern { div => { content: "The body" } }Sean Doyle
-
Fix all Action Text database related models to respect
ActiveRecord::Base.table_name_prefixconfiguration.Chedli Bourguiba
-
Compile ESM package that can be used directly in the browser as actiontext.esm.js
Matias Grunberg
-
Fix using actiontext.js with Sprockets.
Matias Grunberg
-
Upgrade Trix to 2.0.7
Hartley McGuire
-
Fix using Trix with Sprockets.
Hartley McGuire
Railties
-
The new
bin/rails bootcommand boots the application and exits. Supports the standard-e/--environmentoptions.Xavier Noria
-
Create a Dev Container Generator that generates a Dev Container setup based on the current configuration of the application. Usage:
bin/rails devcontainerAndrew Novoselac
-
Add Rubocop and GitHub Actions to plugin generator. This can be skipped using --skip-rubocop and --skip-ci.
Chris Oliver
-
Remove support for
oracle,sqlserverand JRuby specific database adapters from therails newandrails db:system:changecommands.The supported options are
sqlite3,mysql,postgresqlandtrilogy.Andrew Novoselac
-
Add options to
bin/rails app:update.bin/rails app:updatenow supports the same generic options that generators do:--force: Accept all changes to existing files--skip: Refuse all changes to existing files--pretend: Don't make any changes--quiet: Don't output all changes made
Étienne Barrié
-
Implement Rails console commands and helpers with IRB v1.13's extension APIs.
Rails console users will now see
helper,controller,new_session, andappunder IRB help message'sHelper methodscategory. Andreload!command will be displayed under the newRails consolecommands category.Prior to this change, Rails console's commands and helper methods are added through IRB's private components and don't show up in its help message, which led to poor discoverability.
Stan Lo
-
Remove deprecated
Rails::Generators::Testing::Behaviour.Rafael Mendonça França
-
Remove deprecated
find_cmd_and_execconsole helper.Rafael Mendonça França
-
Remove deprecated
Rails.config.enable_dependency_loading.Rafael Mendonça França
-
Remove deprecated
Rails.application.secrets.Rafael Mendonça França
-
Generated Gemfile will include
require: "debug/prelude"for thedebuggem.Requiring
debuggem directly automatically activates it, which could introduce additional overhead and memory usage even without entering a debugging session.By making Bundler require
debug/preludeinstead, developers can keep their access to breakpoint methods likedebuggerorbinding.break, but the debugger won't be activated until a breakpoint is hit.Stan Lo
-
Skip generating a
testjob in ci.yml when a new application is generated with the--skip-testoption.Steve Polito
-
Update the
.node-versionfile conditionally generated for new applications to 20.11.1Steve Polito
-
Fix sanitizer vendor configuration in 7.1 defaults.
In apps where rails-html-sanitizer was not eagerly loaded, the sanitizer default could end up being Rails::HTML4::Sanitizer when it should be set to Rails::HTML5::Sanitizer.
Mike Dalessio, Rafael Mendonça França
-
Set
action_mailer.default_url_optionsvalues indevelopmentandtest.Prior to this commit, new Rails applications would raise
ActionView::Template::Errorif a mailer included a url built with a*_pathhelper.Steve Polito
-
Introduce
Rails::Generators::Testing::Assertions#assert_initializer.Compliments the existing
initializergenerator action.assert_initializer "mail_interceptors.rb"Steve Polito
-
Generate a .devcontainer folder and its contents when creating a new app.
The .devcontainer folder includes everything needed to boot the app and do development in a remote container.
The container setup includes:
- A redis container for Kredis, ActionCable etc.
- A database (SQLite, Postgres, MySQL or MariaDB)
- A Headless chrome container for system tests
- Active Storage configured to use the local disk and with preview features working
If any of these options are skipped in the app setup they will not be included in the container configuration.
These files can be skipped using the
--skip-devcontaineroption.Andrew Novoselac & Rafael Mendonça França
-
Introduce
SystemTestCase#served_byfor configuring the System Test application server.By default this is localhost. This method allows the host and port to be specified manually.
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase served_by host: "testserver", port: 45678 endAndrew Novoselac & Rafael Mendonça França
-
bin/rails testwill no longer load files named*_test.rbif they are located in thefixturesfolder.Edouard Chin
-
Ensure logger tags configured with
config.log_tagsare still active inrequest.action_dispatchhandlers.KJ Tsanaktsidis
-
Setup jemalloc in the default Dockerfile for memory optimization.
Matt Almeida, Jean Boussier
-
Commented out lines in .railsrc file should not be treated as arguments when using rails new generator command. Update ARGVScrubber to ignore text after
#symbols.Willian Tenfen
-
Skip CSS when generating APIs.
Ruy Rocha
-
Rails console now indicates application name and the current Rails environment:
my-app(dev)> # for RAILS_ENV=development my-app(test)> # for RAILS_ENV=test my-app(prod)> # for RAILS_ENV=production my-app(my_env)> # for RAILS_ENV=my_envThe application name is derived from the application's module name from
config/application.rb. For example,MyAppwill displayed asmy-appin the prompt.Additionally, the environment name will be colorized when the environment is
development(blue),test(blue), orproduction(red), if your terminal supports it.Stan Lo
-
Ensure
autoload_paths,autoload_once_paths,eager_load_paths, andload_pathsonly have directories when initialized from engine defaults.Previously, files under the
appdirectory could end up there too.Takumasa Ochi
-
Prevent unnecessary application reloads in development.
Previously, some files outside autoload paths triggered unnecessary reloads. With this fix, application reloads according to
Rails.autoloaders.main.dirs, thereby preventing unnecessary reloads.Takumasa Ochi
-
Use
oven-sh/setup-bunin GitHub CI when generating an app with Bun.TangRufus
-
Disable
pidfilegeneration in theproductionenvironment.Hans Schnedlitz
-
Set
config.action_view.annotate_rendered_view_with_filenamestotruein thedevelopmentenvironment.Adrian Marin
-
Support the
BACKTRACEenvironment variable to turn off backtrace cleaning.Useful for debugging framework code:
BACKTRACE=1 bin/rails serverAlex Ghiculescu
-
Raise
ArgumentErrorwhen readingconfig.x.somethingwith arguments:config.x.this_works.this_raises true # raises ArgumentErrorSean Doyle
-
Add default PWA files for manifest and service-worker that are served from
app/views/pwaand can be dynamically rendered through ERB. Mount these files explicitly at the root with default routes in the generated routes file.DHH
-
Updated system tests to now use headless Chrome by default for the new applications.
DHH
-
Add GitHub CI files for Dependabot, Brakeman, RuboCop, and running tests by default. Can be skipped with
--skip-ci.DHH
-
Add Brakeman by default for static analysis of security vulnerabilities. Allow skipping with
--skip-brakeman option.vipulnsward
-
Add RuboCop with rules from
rubocop-rails-omakaseby default. Skip with--skip-rubocop.DHH and zzak
-
Use
bin/rails runner --skip-executorto not wrap the runner script with an Executor.Ben Sheldon
-
Fix isolated engines to take
ActiveRecord::Base.table_name_prefixinto consideration.This will allow for engine defined models, such as inside Active Storage, to respect Active Record table name prefix configuration.
Chedli Bourguiba
-
Fix running
db:system:changewhen the app has no Dockerfile.Hartley McGuire
-
In Action Mailer previews, list inline attachments separately from normal attachments.
For example, attachments that were previously listed like
Attachments: logo.png file1.pdf file2.pdf
will now be listed like
Attachments: file1.pdf file2.pdf (Inline: logo.png)
Christian Schmidt and Jonathan Hefner
-
In mailer preview, only show SMTP-To if it differs from the union of To, Cc and Bcc.
Christian Schmidt
-
Enable YJIT by default on new applications running Ruby 3.3+.
This can be disabled by setting
Rails.application.config.yjit = falseJean Boussier, Rafael Mendonça França
-
In Action Mailer previews, show date from message
Dateheader if present.Sampat Badhe
-
Exit with non-zero status when the migration generator fails.
Katsuhiko YOSHIDA
-
Use numeric UID and GID in Dockerfile template.
The Dockerfile generated by
rails newsets the default user and group by name instead of UID:GID. This can cause the following error in Kubernetes:container has runAsNonRoot and image has non-numeric user (rails), cannot verify user is non-rootThis change sets default user and group by their numeric values.
Ivan Fedotov
-
Disallow invalid values for rails new options.
The
--database,--asset-pipeline,--css, and--javascriptoptions forrails newtake different arguments. This change validates them.Tony Drake, Akhil G Krishnan, Petrik de Heus
-
Conditionally print
$stdoutwhen invokingrun_generator.In an effort to improve the developer experience when debugging generator tests, we add the ability to conditionally print
$stdoutinstead of capturing it.This allows for calls to
binding.irbandputswork as expected.RAILS_LOG_TO_STDOUT=true ./bin/test test/generators/actions_test.rbSteve Polito
-
Remove the option
config.public_file_server.enabledfrom the generators for all environments, as the value is the same in all environments.Adrian Hirt