Compare Versions - rails
RubyGems / rails / Compare Versions
Active Support
-
Make
delegateanddelegate_missing_towork in BasicObject subclasses.Rafael Mendonça França
-
Fix Inflectors when using a locale that fallbacks to
:en.Said Kaldybaev
-
Fix
ActiveSupport::TimeWithZone#as_jsonto consistently return UTF-8 strings.Previously the returned string would sometime be encoded in US-ASCII, which in some cases may be problematic.
Now the method consistently always return UTF-8 strings.
Jean Boussier
-
Fix
TimeWithZone#xmlschemawhen wrapping aDateTimeinstance in local time.Previously it would return an invalid time.
Dmytro Rymar
-
Implement LocalCache strategy on
ActiveSupport::Cache::MemoryStore. The memory store needs to respond to the same interface as other cache stores (e.g.ActiveSupport::NullStore).Mikey Gough
-
Fix
ActiveSupport::Inflector.humanizewith international characters.ActiveSupport::Inflector.humanize("áÉÍÓÚ") # => "Áéíóú" ActiveSupport::Inflector.humanize("аБВГДЕ") # => "Абвгде"Jose Luis Duran
Active Model
- No changes.
Active Record
-
Fix counting cached queries in
ActiveRecord::RuntimeRegistry.fatkodima
-
Fix merging relations with arel equality predicates with null relations.
fatkodima
-
Fix SQLite3 schema dump for non-autoincrement integer primary keys.
Previously,
schema.rbshould incorrectly restore that table with an auto incrementing primary key.Chris Hasiński
-
Fix PostgreSQL
schema_search_pathnot being reapplied afterreset!orreconnect!.The
schema_search_pathconfigured indatabase.ymlis now correctly reapplied instead of falling back to PostgreSQL defaults.Tobias Egli
-
Restore the ability of enum to be foats.
enum :rating, { low: 0.0, medium: 0.5, high: 1.0 },In Rails 8.1.0, enum values are eagerly validated, and floats weren't expected.
Said Kaldybaev
-
Ensure batched preloaded associations accounts for klass when grouping to avoid issues with STI.
zzak, Stjepan Hadjic
-
Fix
ActiveRecord::SoleRecordExceeded#recordto return the relation.This was the case until Rails 7.2, but starting from 8.0 it started mistakenly returning the model class.
Jean Boussier
-
Improve PostgreSQLAdapter resilience to Timeout.timeout.
Better handle asynchronous exceptions being thrown inside the
reconnect!method.This may fixes some deep errors such as:
undefined method `key?' for nil:NilClass (NoMethodError) if !type_map.key?(oid)Jean Boussier
-
Fix structured events for Active Record was not being emitted.
Yuji Yaginuma
-
Fix
eager_loadwhen loadinghas_manyassocations with composite primary keys.This would result in some records being loaded multiple times.
Martin-Alexander
Action View
-
Fix
file_fieldto join mime types with a comma when provided as Arrayfile_field(:article, :image, accept: ['image/png', 'image/gif', 'image/jpeg'])Now behaves likes:
file_field(:article, :image, accept: 'image/png,image/gif,image/jpeg')Bogdan Gusiev
-
Fix strict locals parsing to handle multiline definitions.
Said Kaldybaev
-
Fix
content_security_policy_nonceerror in mailers when usingcontent_security_policy_nonce_autosetting.The
content_security_policy_nonce helperis provided byActionController::ContentSecurityPolicy, and it relies onrequest.content_security_policy_nonce. Mailers lack both the module and the request object.Jarrett Lusso
Action Pack
-
Add
config.action_controller.live_streaming_excluded_keysto control execution state sharing in ActionController::Live.When using ActionController::Live, actions are executed in a separate thread that shares state from the parent thread. This new configuration allows applications to opt-out specific state keys that should not be shared.
This is useful when streaming inside a
connected_toblock, where you may want the streaming thread to use its own database connection context.# config/application.rb config.action_controller.live_streaming_excluded_keys = [:active_record_connected_to_stack]By default, all keys are shared.
Eileen M. Uchitelle
-
Fix
IpSpoofAttackErrormessage to includeForwardedheader content.Without it, the error message may be misleading.
zzak
Active Job
-
Fix
ActiveJob.perform_all_laterto respectjob_class.enqueue_after_transaction_commit.Previously,
perform_all_laterwould enqueue all jobs immediately, even if they hadenqueue_after_transaction_commit = true. Now it correctly defers jobs with this setting until after transaction commits, matching the behavior ofperform_later.OuYangJinTing
-
Fix using custom serializers with
ActiveJob::Arguments.serializewhenActiveJob::Basehasn't been loaded.Hartley McGuire
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Restore ADC when signing URLs with IAM for GCS
ADC was previously used for automatic authorization when signing URLs with IAM. Now it is again, but the auth client is memoized so that new credentials are only requested when the current ones expire. Other auth methods can now be used instead by setting the authorization on
ActiveStorage::Service::GCSService#iam_client.ActiveStorage::Blob.service.iam_client.authorization = Google::Auth::ImpersonatedServiceAccountCredentials.new(options)This is safer than setting
Google::Apis::RequestOptions.default.authorizationbecause it only applies to Active Storage and does not affect other Google API clients.Justin Malčić
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Skip all system test files on app generation.
Eileen M. Uchitelle
-
Fix
db:system:changeto correctly update Dockerfile base packages.Josiah Smith
-
Fix devcontainer volume mount when app name differs from folder name.
Rafael Mendonça França
-
Fixed the
rails notescommand to properly extract notes in CSS files.David White
-
Fixed the default Dockerfile to properly include the
vendor/directory duringbundle install.Zhong Sheng
Guides
- No changes.
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
-
Respect
remove_hidden_field_autocompleteconfig in form builderhidden_field.Rafael Mendonça França
Action Pack
-
Allow methods starting with underscore to be action methods.
Disallowing methods starting with an underscore from being action methods was an unintended side effect of the performance optimization in 207a254.
Fixes #55985.
Rafael Mendonça França
Active Job
-
Only index new serializers.
Jesse Sharps
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Do not assume and force SSL in production by default when using Kamal, to allow for out of the box Kamal deployments.
It is still recommended to assume and force SSL in production as soon as you can.
Jerome Dalbert
Guides
- No changes.
Active Support
-
Remove deprecated passing a Time object to
Time#since.Rafael Mendonça França
-
Remove deprecated
Benchmark.msmethod. It is now defined in thebenchmarkgem.Rafael Mendonça França
-
Remove deprecated addition for
Timeinstances withActiveSupport::TimeWithZone.Rafael Mendonça França
-
Remove deprecated support for
to_timeto preserve the system local time. It will now always preserve the receiver timezone.Rafael Mendonça França
-
Deprecate
config.active_support.to_time_preserves_timezone.Rafael Mendonça França
-
Standardize event name formatting in
assert_event_reportederror messages.The event name in failure messages now uses
.inspect(e.g.,name: "user.created") to matchassert_events_reportedand provide type clarity between strings and symbols. This only affects tests that assert on the failure message format itself.George Ma
-
Fix
Enumerable#soleto return the full tuple instead of just the first element of the tuple.Olivier Bellone
-
Fix parallel tests hanging when worker processes die abruptly.
Previously, if a worker process was killed (e.g., OOM killed,
kill -9) during parallel test execution, the test suite would hang forever waiting for the dead worker.Joshua Young
-
Add
config.active_support.escape_js_separators_in_json.Introduce a new framework default to skip escaping LINE SEPARATOR (U+2028) and PARAGRAPH SEPARATOR (U+2029) in JSON.
Historically these characters were not valid inside JavaScript literal strings but that changed in ECMAScript 2019. As such it's no longer a concern in modern browsers: https://caniuse.com/mdn-javascript_builtins_json_json_superset.
Étienne Barrié, Jean Boussier
-
Fix
NameErrorwhenclass_attributeis defined on instance singleton classes.Previously, calling
class_attributeon an instance's singleton class would raise aNameErrorwhen accessing the attribute through the instance.object = MyClass.new object.singleton_class.class_attribute :foo, default: "bar" object.foo # previously raised NameError, now returns "bar"Joshua Young
-
Introduce
ActiveSupport::Testing::EventReporterAssertions#with_debug_event_reportingto enable event reporter debug mode in tests.The previous way to enable debug mode is by using
#with_debugon the event reporter itself, which is too verbose. This new helper will help clear up any confusion on how to test debug events.Gannon McGibbon
-
Add
ActiveSupport::StructuredEventSubscriberfor consuming notifications and emitting structured event logs. Events may be emitted with the#emit_eventor#emit_debug_eventmethods.class MyStructuredEventSubscriber < ActiveSupport::StructuredEventSubscriber def notification(event) emit_event("my.notification", data: 1) end endAdrianna Chang
-
ActiveSupport::FileUpdateCheckerdoes not depend onTime.nowto prevent unecessary reloads with time travel test helpersJan Grodowski
-
Add
ActiveSupport::Cache::Store#namespace=and#namespace.Can be used as an alternative to
Store#clearin some situations such as parallel testing.Nick Schwaderer
-
Create
parallel_worker_idhelper for running parallel tests. This allows users to know which worker they are currently running in.Nick Schwaderer
-
Make the cache of
ActiveSupport::Cache::Strategy::LocalCache::Middlewareupdatable.If the cache client at
Rails.cacheof a booted application changes, the corresponding mounted middleware needs to update in order for request-local caches to be setup properly. Otherwise, redundant cache operations will erroneously hit the datastore.Gannon McGibbon
-
Add
assert_events_reportedtest helper forActiveSupport::EventReporter.This new assertion allows testing multiple events in a single block, regardless of order:
assert_events_reported([ { name: "user.created", payload: { id: 123 } }, { name: "email.sent", payload: { to: "user@example.com" } } ]) do create_user_and_send_welcome_email endGeorge Ma
-
Add
ActiveSupport::TimeZone#standard_namemethod.zone = ActiveSupport::TimeZone['Hawaii'] # Old way ActiveSupport::TimeZone::MAPPING[zone.name] # New way zone.standard_name # => 'Pacific/Honolulu'Bogdan Gusiev
-
Add Structured Event Reporter, accessible via
Rails.event.The Event Reporter provides a unified interface for producing structured events in Rails applications:
Rails.event.notify("user.signup", user_id: 123, email: "user@example.com")It supports adding tags to events:
Rails.event.tagged("graphql") do # Event includes tags: { graphql: true } Rails.event.notify("user.signup", user_id: 123, email: "user@example.com") endAs well as context:
# All events will contain context: {request_id: "abc123", shop_id: 456} Rails.event.set_context(request_id: "abc123", shop_id: 456)Events are emitted to subscribers. Applications register subscribers to control how events are serialized and emitted. Subscribers must implement an
#emitmethod, which receives the event hash:class LogSubscriber def emit(event) payload = event[:payload].map { |key, value| "#{key}=#{value}" }.join(" ") source_location = event[:source_location] log = "[#{event[:name]}] #{payload} at #{source_location[:filepath]}:#{source_location[:lineno]}" Rails.logger.info(log) end endAdrianna Chang
-
Make
ActiveSupport::Logger#freeze-friendly.Joshua Young
-
Make
ActiveSupport::Gzip.compressdeterministic based on input.ActiveSupport::Gzip.compressused to include a timestamp in the output, causing consecutive calls with the same input data to have different output if called during different seconds. It now always sets the timestamp to0so that the output is identical for any given input.Rob Brackett
-
Given an array of
Thread::Backtrace::Locationobjects, the new methodActiveSupport::BacktraceCleaner#clean_locationsreturns an array with the clean ones:clean_locations = backtrace_cleaner.clean_locations(caller_locations)Filters and silencers receive strings as usual. However, the
pathattributes of the locations in the returned array are the original, unfiltered ones, since locations are immutable.Xavier Noria
-
Improve
CurrentAttributesandExecutionContextstate managment in test cases.Previously these two global state would be entirely cleared out whenever calling into code that is wrapped by the Rails executor, typically Action Controller or Active Job helpers:
test "#index works" do CurrentUser.id = 42 get :index CurrentUser.id == nil endNow re-entering the executor properly save and restore that state.
Jean Boussier
-
The new method
ActiveSupport::BacktraceCleaner#first_clean_locationreturns the first clean location of the caller's call stack, ornil. Locations areThread::Backtrace::Locationobjects. Useful when you want to report the application-level location where something happened as an object.Xavier Noria
-
FileUpdateChecker and EventedFileUpdateChecker ignore changes in Gem.path now.
Ermolaev Andrey, zzak
-
The new method
ActiveSupport::BacktraceCleaner#first_clean_framereturns the first clean frame of the caller's backtrace, ornil. Useful when you want to report the application-level frame where something happened as a string.Xavier Noria
-
Always clear
CurrentAttributesinstances.Previously
CurrentAttributesinstance would be reset at the end of requests. Meaning its attributes would be re-initialized.This is problematic because it assume these objects don't hold any state other than their declared attribute, which isn't always the case, and can lead to state leak across request.
Now
CurrentAttributesinstances are abandoned at the end of a request, and a new instance is created at the start of the next request.Jean Boussier, Janko Marohnić
-
Add public API for
before_fork_hookin parallel testing.Introduces a public API for calling the before fork hooks implemented by parallel testing.
parallelize_before_fork do # perform an action before test processes are forked endEileen M. Uchitelle
-
Implement ability to skip creating parallel testing databases.
With parallel testing, Rails will create a database per process. If this isn't desirable or you would like to implement databases handling on your own, you can now turn off this default behavior.
To skip creating a database per process, you can change it via the
parallelizemethod:parallelize(workers: 10, parallelize_databases: false)or via the application configuration:
config.active_support.parallelize_databases = falseEileen M. Uchitelle
-
Allow to configure maximum cache key sizes
When the key exceeds the configured limit (250 bytes by default), it will be truncated and the digest of the rest of the key appended to it.
Note that previously
ActiveSupport::Cache::RedisCacheStoreallowed up to 1kb cache keys before truncation, which is now reduced to 250 bytes.config.cache_store = :redis_cache_store, { max_key_size: 64 }fatkodima
-
Use
UNLINKcommand instead ofDELinActiveSupport::Cache::RedisCacheStorefor non-blocking deletion.Aron Roh
-
Add
Cache#read_counterandCache#write_counterRails.cache.write_counter("foo", 1) Rails.cache.read_counter("foo") # => 1 Rails.cache.increment("foo") Rails.cache.read_counter("foo") # => 2Alex Ghiculescu
-
Introduce ActiveSupport::Testing::ErrorReporterAssertions#capture_error_reports
Captures all reported errors from within the block that match the given error class.
reports = capture_error_reports(IOError) do Rails.error.report(IOError.new("Oops")) Rails.error.report(IOError.new("Oh no")) Rails.error.report(StandardError.new) end assert_equal 2, reports.size assert_equal "Oops", reports.first.error.message assert_equal "Oh no", reports.last.error.messageAndrew Novoselac
-
Introduce ActiveSupport::ErrorReporter#add_middleware
When reporting an error, the error context middleware will be called with the reported error and base execution context. The stack may mutate the context hash. The mutated context will then be passed to error subscribers. Middleware receives the same parameters as
ErrorReporter#report.Andrew Novoselac, Sam Schmidt
-
Change execution wrapping to report all exceptions, including
Exception.If a more serious error like
SystemStackErrororNoMemoryErrorhappens, the error reporter should be able to report these kinds of exceptions.Gannon McGibbon
-
ActiveSupport::Testing::Parallelization.before_fork_hookallows declaration of callbacks that are invoked immediately before forking test workers.Mike Dalessio
-
Allow the
#freeze_timetesting helper to accept a date or time argument.Time.current # => Sun, 09 Jul 2024 15:34:49 EST -05:00 freeze_time Time.current + 1.day sleep 1 Time.current # => Mon, 10 Jul 2024 15:34:49 EST -05:00Joshua Young
-
ActiveSupport::JSONnow accepts optionsIt is now possible to pass options to
ActiveSupport::JSON:ActiveSupport::JSON.decode('{"key": "value"}', symbolize_names: true) # => { key: "value" }matthaigh27
-
ActiveSupport::Testing::NotificationAssertions'sassert_notificationnow matches against payload subsets by default.Previously the following assertion would fail due to excess key vals in the notification payload. Now with payload subset matching, it will pass.
assert_notification("post.submitted", title: "Cool Post") do ActiveSupport::Notifications.instrument("post.submitted", title: "Cool Post", body: "Cool Body") endAdditionally, you can now persist a matched notification for more customized assertions.
notification = assert_notification("post.submitted", title: "Cool Post") do ActiveSupport::Notifications.instrument("post.submitted", title: "Cool Post", body: Body.new("Cool Body")) end assert_instance_of(Body, notification.payload[:body])Nicholas La Roux
-
Deprecate
String#mb_charsandActiveSupport::Multibyte::Chars.These APIs are a relic of the Ruby 1.8 days when Ruby strings weren't encoding aware. There is no legitimate reasons to need these APIs today.
Jean Boussier
-
Deprecate
ActiveSupport::ConfigurableSean Doyle
-
nil.to_query("key")now returnskey.Previously it would return
key=, preventing round tripping withRack::Utils.parse_nested_query.Erol Fornoles
-
Avoid wrapping redis in a
ConnectionPoolwhen usingActiveSupport::Cache::RedisCacheStoreif the:redisoption is already aConnectionPool.Joshua Young
-
Alter
ERB::Util.tokenizeto return :PLAIN token with full input string when string doesn't contain ERB tags.Martin Emde
-
Fix a bug in
ERB::Util.tokenizethat causes incorrect tokenization when ERB tags are preceded by multibyte characters.Martin Emde
-
Add
ActiveSupport::Testing::NotificationAssertionsmodule to help with testingActiveSupport::Notifications.Nicholas La Roux, Yishu See, Sean Doyle
-
ActiveSupport::CurrentAttributes#attributesnow will return a new hash object on each call.Previously, the same hash object was returned each time that method was called.
fatkodima
-
ActiveSupport::JSON.encodesupports CIDR notation.Previously:
ActiveSupport::JSON.encode(IPAddr.new("172.16.0.0/24")) # => "\"172.16.0.0\""After this change:
ActiveSupport::JSON.encode(IPAddr.new("172.16.0.0/24")) # => "\"172.16.0.0/24\""Taketo Takashima
-
Make
ActiveSupport::FileUpdateCheckerfaster when checking many file-extensions.Jonathan del Strother
Active Model
-
Add
reset_token: { expires_in: ... }option tohas_secure_password.Allows configuring the expiry duration of password reset tokens (default remains 15 minutes for backwards compatibility).
has_secure_password reset_token: { expires_in: 1.hour }Jevin Sew, Abeid Ahmed
-
Add
except_on:option for validation callbacks.Ben Sheldon
-
Backport
ActiveRecord::NormalizationtoActiveModel::Attributes::Normalizationclass User include ActiveModel::Attributes include ActiveModel::Attributes::Normalization attribute :email, :string normalizes :email, with: -> email { email.strip.downcase } end user = User.new user.email = " CRUISE-CONTROL@EXAMPLE.COM\n" user.email # => "cruise-control@example.com"Sean Doyle
Active Record
-
Fix SQLite3 data loss during table alterations with CASCADE foreign keys.
When altering a table in SQLite3 that is referenced by child tables with
ON DELETE CASCADEforeign keys, ActiveRecord would silently delete all data from the child tables. This occurred because SQLite requires table recreation for schema changes, and during this process the original table is temporarily dropped, triggering CASCADE deletes on child tables.The root cause was incorrect ordering of operations. The original code wrapped
disable_referential_integrityinside a transaction, butPRAGMA foreign_keyscannot be modified inside a transaction in SQLite - attempting to do so simply has no effect. This meant foreign keys remained enabled during table recreation, causing CASCADE deletes to fire.The fix reverses the order to follow the official SQLite 12-step ALTER TABLE procedure:
disable_referential_integritynow wraps the transaction instead of being wrapped by it. This ensures foreign keys are properly disabled before the transaction starts and re-enabled after it commits, preventing CASCADE deletes while maintaining data integrity through atomic transactions.Ruy Rocha
-
Add replicas to test database parallelization setup.
Setup and configuration of databases for parallel testing now includes replicas.
This fixes an issue when using a replica database, database selector middleware, and non-transactional tests, where integration tests running in parallel would select the base test database, i.e.
db_test, instead of the numbered parallel worker database, i.e.db_test_{n}.Adam Maas
-
Support virtual (not persisted) generated columns on PostgreSQL 18+
PostgreSQL 18 introduces virtual (not persisted) generated columns, which are now the default unless the
stored: trueoption is explicitly specified on PostgreSQL 18+.create_table :users do |t| t.string :name t.virtual :lower_name, type: :string, as: "LOWER(name)", stored: false t.virtual :name_length, type: :integer, as: "LENGTH(name)" endYasuo Honda
-
Optimize schema dumping to prevent duplicate file generation.
ActiveRecord::Tasks::DatabaseTasks.dump_allnow tracks which schema files have already been dumped and skips dumping the same file multiple times. This improves performance when multiple database configurations share the same schema dump path.Mikey Gough, Hartley McGuire
-
Add structured events for Active Record:
active_record.strict_loading_violationactive_record.sql
Gannon McGibbon
-
Add support for integer shard keys.
# Now accepts symbols as shard keys. ActiveRecord::Base.connects_to(shards: { 1: { writing: :primary_shard_one, reading: :primary_shard_one }, 2: { writing: :primary_shard_two, reading: :primary_shard_two}, }) ActiveRecord::Base.connected_to(shard: 1) do # .. endNony Dutton
-
Add
ActiveRecord::Base.only_columnsSimilar in use case to
ignored_columnsbut listing columns to consider rather than the ones to ignore.Can be useful when working with a legacy or shared database schema, or to make safe schema change in two deploys rather than three.
Anton Kandratski
-
Use
PG::Connection#close_prepared(protocol level Close) to deallocate prepared statements when available.To enable its use, you must have pg >= 1.6.0, libpq >= 17, and a PostgreSQL database version >= 17.
Hartley McGuire, Andrew Jackson
-
Fix query cache for pinned connections in multi threaded transactional tests
When a pinned connection is used across separate threads, they now use a separate cache store for each thread.
This improve accuracy of system tests, and any test using multiple threads.
Heinrich Lee Yu, Jean Boussier
-
Fix time attribute dirty tracking with timezone conversions.
Time-only attributes now maintain a fixed date of 2000-01-01 during timezone conversions, preventing them from being incorrectly marked as changed due to date shifts.
This fixes an issue where time attributes would be marked as changed when setting the same time value due to timezone conversion causing internal date shifts.
Prateek Choudhary
-
Skip calling
PG::Connection#cancelincancel_any_running_querywhen using libpq >= 18 with pg < 1.6.0, due to incompatibility. Rollback still runs, but may take longer.Yasuo Honda, Lars Kanis
-
Don't add
id_valueattribute alias when attribute/column with that name already exists.Rob Lewis
-
Remove deprecated
:unsigned_floatand:unsigned_decimalcolumn methods for MySQL.Rafael Mendonça França
-
Remove deprecated
:retriesoption for the SQLite3 adapter.Rafael Mendonça França
-
Introduce new database configuration options
keepalive,max_age, andmin_connections-- and renamepooltomax_connectionsto match.There are no changes to default behavior, but these allow for more specific control over pool behavior.
Matthew Draper, Chris AtLee, Rachael Wright-Munn
-
Move
LIMITvalidation from query generation to whenlimit()is called.Hartley McGuire, Shuyang
-
Add
ActiveRecord::CheckViolationerror class for check constraint violations.Ryuta Kamizono
-
Add
ActiveRecord::ExclusionViolationerror class for exclusion constraint violations.When an exclusion constraint is violated in PostgreSQL, the error will now be raised as
ActiveRecord::ExclusionViolationinstead of the genericActiveRecord::StatementInvalid, making it easier to handle these specific constraint violations in application code.This follows the same pattern as other constraint violation error classes like
RecordNotUniquefor unique constraint violations andInvalidForeignKeyfor foreign key constraint violations.Ryuta Kamizono
-
Attributes filtered by
filter_attributeswill now also be filtered byfilter_parametersso sensitive information is not leaked.Jill Klang
-
Add
connection.current_transaction.isolationAPI to check current transaction's isolation level.Returns the isolation level if it was explicitly set via the
isolation:parameter or throughActiveRecord.with_transaction_isolation_level, otherwise returnsnil. Nested transactions return the parent transaction's isolation level.# Returns nil when no transaction User.connection.current_transaction.isolation # => nil # Returns explicitly set isolation level User.transaction(isolation: :serializable) do User.connection.current_transaction.isolation # => :serializable end # Returns nil when isolation not explicitly set User.transaction do User.connection.current_transaction.isolation # => nil end # Nested transactions inherit parent's isolation User.transaction(isolation: :read_committed) do User.transaction do User.connection.current_transaction.isolation # => :read_committed end endKir Shatrov
-
Fix
#mergewith#oror#andand a mixture of attributes and SQL strings resulting in an incorrect query.base = Comment.joins(:post).where(user_id: 1).where("recent = 1") puts base.merge(base.where(draft: true).or(Post.where(archived: true))).to_sqlBefore:
SELECT "comments".* FROM "comments" INNER JOIN "posts" ON "posts"."id" = "comments"."post_id" WHERE (recent = 1) AND ( "comments"."user_id" = 1 AND (recent = 1) AND "comments"."draft" = 1 OR "posts"."archived" = 1 )After:
SELECT "comments".* FROM "comments" INNER JOIN "posts" ON "posts"."id" = "comments"."post_id" WHERE "comments"."user_id" = 1 AND (recent = 1) AND ( "comments"."user_id" = 1 AND (recent = 1) AND "comments"."draft" = 1 OR "posts"."archived" = 1 )Joshua Young
-
Make schema dumper to account for
ActiveRecord.dump_schemaswhen dumping in:rubyformat.fatkodima
-
Add
:touchoption toupdate_column/update_columnsmethods.# Will update :updated_at/:updated_on alongside :nice column. user.update_column(:nice, true, touch: true) # Will update :updated_at/:updated_on alongside :last_ip column user.update_columns(last_ip: request.remote_ip, touch: true)Dmitrii Ivliev
-
Optimize Active Record batching further when using ranges.
Tested on a PostgreSQL table with 10M records and batches of 10k records, the generation of relations for the 1000 batches was
4.8xfaster (6.8svs.1.4s), used900xless bandwidth (180MBvs.0.2MB) and allocated45xless memory (490MBvs.11MB).Maxime Réty, fatkodima
-
Include current character length in error messages for index and table name length validations.
Joshua Young
-
Add
rename_schemamethod for PostgreSQL.T S Vallender
-
Implement support for deprecating associations:
has_many :posts, deprecated: trueWith that, Active Record will report any usage of the
postsassociation.Three reporting modes are supported (
:warn,:raise, and:notify), and backtraces can be enabled or disabled. Defaults are:warnmode and disabled backtraces.Please, check the docs for further details.
Xavier Noria
-
PostgreSQL adapter create DB now supports
locale_providerandlocale.Bengt-Ove Hollaender
-
Use ntuples to populate row_count instead of count for Postgres
Jonathan Calvert
-
Fix checking whether an unpersisted record is
include?d in a strictly loadedhas_and_belongs_to_manyassociation.Hartley McGuire
-
Add ability to change transaction isolation for all pools within a block.
This functionality is useful if your application needs to change the database transaction isolation for a request or action.
Calling
ActiveRecord.with_transaction_isolation_level(level) {}in an around filter or middleware will set the transaction isolation for all pools accessed within the block, but not for the pools that aren't.This works with explicit and implicit transactions:
ActiveRecord.with_transaction_isolation_level(:read_committed) do Tag.transaction do # opens a transaction explicitly Tag.create! end endActiveRecord.with_transaction_isolation_level(:read_committed) do Tag.create! # opens a transaction implicitly endEileen M. Uchitelle
-
Raise
ActiveRecord::MissingRequiredOrderErrorwhen order dependent finder methods (e.g.#first,#last) are called withoutordervalues on the relation, and the model does not have any order columns (implicit_order_column,query_constraints, orprimary_key) to fall back on.This change will be introduced with a new framework default for Rails 8.1, and the current behavior of not raising an error has been deprecated with the aim of removing the configuration option in Rails 8.2.
config.active_record.raise_on_missing_required_finder_order_columns = trueJoshua Young
-
:class_nameis now invalid in polymorphicbelongs_toassociations.Reason is
:class_namedoes not make sense in those associations because the class name of target records is dynamic and stored in the type column.Existing polymorphic associations setting this option can just delete it. While it did not raise, it had no effect anyway.
Xavier Noria
-
Add support for multiple databases to
db:migrate:reset.Joé Dupuis
-
Add
affected_rowstoActiveRecord::Result.Jenny Shen
-
Enable passing retryable SqlLiterals to
#where.Hartley McGuire
-
Set default for primary keys in
insert_all/upsert_all.Previously in Postgres, updating and inserting new records in one upsert wasn't possible due to null primary key values.
nilprimary key values passed intoinsert_all/upsert_allare now implicitly set to the default insert value specified by adapter.Jenny Shen
-
Add a load hook
active_record_database_configurationsforActiveRecord::DatabaseConfigurationsMike Dalessio
-
Use
TRUEandFALSEfor SQLite queries with boolean columns.Hartley McGuire
-
Bump minimum supported SQLite to 3.23.0.
Hartley McGuire
-
Allow allocated Active Records to lookup associations.
Previously, the association cache isn't setup on allocated record objects, so association lookups will crash. Test frameworks like mocha use allocate to check for stubbable instance methods, which can trigger an association lookup.
Gannon McGibbon
-
Encryption now supports
support_unencrypted_data: truebeing set per-attribute.Previously this only worked if
ActiveRecord::Encryption.config.support_unencrypted_data == true. Now, if the global config is turned off, you can still opt in for a specific attribute.# ActiveRecord::Encryption.config.support_unencrypted_data = true class User < ActiveRecord::Base encrypts :name, support_unencrypted_data: false # only supports encrypted data encrypts :email # supports encrypted or unencrypted data end# ActiveRecord::Encryption.config.support_unencrypted_data = false class User < ActiveRecord::Base encrypts :name, support_unencrypted_data: true # supports encrypted or unencrypted data encrypts :email # only supports encrypted data endAlex Ghiculescu
-
Model generator no longer needs a database connection to validate column types.
Mike Dalessio
-
Allow signed ID verifiers to be configurable via
Rails.application.message_verifiersPrior to this change, the primary way to configure signed ID verifiers was to set
signed_id_verifieron each model class:Post.signed_id_verifier = ActiveSupport::MessageVerifier.new(...) Comment.signed_id_verifier = ActiveSupport::MessageVerifier.new(...)And if the developer did not set
signed_id_verifier, a verifier would be instantiated with a secret derived fromsecret_key_baseand the following options:{ digest: "SHA256", serializer: JSON, url_safe: true }Thus it was cumbersome to rotate configuration for all verifiers.
This change defines a new Rails config:
config.active_record.use_legacy_signed_id_verifier. The default value is:generate_and_verify, which preserves the previous behavior. However, when set to:verify, signed ID verifiers will use configuration fromRails.application.message_verifiers(specifically,Rails.application.message_verifiers["active_record/signed_id"]) to generate and verify signed IDs, but will also verify signed IDs using the older configuration.To avoid complication, the new behavior only applies when
signed_id_verifier_secretis not set on a model class or any of its ancestors. Additionally,signed_id_verifier_secretis now deprecated. If you are currently settingsigned_id_verifier_secreton a model class, you can setsigned_id_verifierinstead:# BEFORE Post.signed_id_verifier_secret = "my secret" # AFTER Post.signed_id_verifier = ActiveSupport::MessageVerifier.new("my secret", digest: "SHA256", serializer: JSON, url_safe: true)To ease migration,
signed_id_verifierhas also been changed to behave as aclass_attribute(i.e. inheritable), but only whensigned_id_verifier_secretis not set:# BEFORE ActiveRecord::Base.signed_id_verifier = ActiveSupport::MessageVerifier.new(...) Post.signed_id_verifier == ActiveRecord::Base.signed_id_verifier # => false # AFTER ActiveRecord::Base.signed_id_verifier = ActiveSupport::MessageVerifier.new(...) Post.signed_id_verifier == ActiveRecord::Base.signed_id_verifier # => true Post.signed_id_verifier_secret = "my secret" # => deprecation warning Post.signed_id_verifier == ActiveRecord::Base.signed_id_verifier # => falseNote, however, that it is recommended to eventually migrate from model-specific verifiers to a unified configuration managed by
Rails.application.message_verifiers.ActiveSupport::MessageVerifier#rotatecan facilitate that transition. For example:# BEFORE # Generate and verify signed Post IDs using Post-specific configuration Post.signed_id_verifier = ActiveSupport::MessageVerifier.new("post secret", ...) # AFTER # Generate and verify signed Post IDs using the unified configuration Post.signed_id_verifier = Post.signed_id_verifier.dup # Fall back to Post-specific configuration when verifying signed IDs Post.signed_id_verifier.rotate("post secret", ...)Ali Sepehri, Jonathan Hefner
-
Prepend
extra_flagsin postgres'structure_loadWhen specifying
structure_load_flagswith a postgres adapter, the flags were appended to the default flags, instead of prepended. This caused issues with flags not being taken into account by postgres.Alice Loeser
-
Allow bypassing primary key/constraint addition in
implicit_order_columnWhen specifying multiple columns in an array for
implicit_order_column, addingnilas the last element will prevent appending the primary key to order conditions. This allows more precise control of indexes used by generated queries. It should be noted that this feature does introduce the risk of API misbehavior if the specified columns are not fully unique.Issy Long
-
Allow setting the
schema_formatvia database configuration.primary: schema_format: rubyUseful for multi-database setups when apps require different formats per-database.
T S Vallender
-
Support disabling indexes for MySQL v8.0.0+ and MariaDB v10.6.0+
MySQL 8.0.0 added an option to disable indexes from being used by the query optimizer by making them "invisible". This allows the index to still be maintained and updated but no queries will be permitted to use it. This can be useful for adding new invisible indexes or making existing indexes invisible before dropping them to ensure queries are not negatively affected. See https://dev.mysql.com/blog-archive/mysql-8-0-invisible-indexes/ for more details.
MariaDB 10.6.0 also added support for this feature by allowing indexes to be "ignored" in queries. See https://mariadb.com/kb/en/ignored-indexes/ for more details.
Active Record now supports this option for MySQL 8.0.0+ and MariaDB 10.6.0+ for index creation and alteration where the new index option
enabled: true/falsecan be passed to column and index methods as below:add_index :users, :email, enabled: false enable_index :users, :email add_column :users, :dob, :string, index: { enabled: false } change_table :users do |t| t.index :name, enabled: false t.index :dob t.disable_index :dob t.column :username, :string, index: { enabled: false } t.references :account, index: { enabled: false } end create_table :users do |t| t.string :name, index: { enabled: false } t.string :email t.index :email, enabled: false endMerve Taner
-
Respect
implicit_order_columninActiveRecord::Relation#reverse_order.Joshua Young
-
Add column types to
ActiveRecord::Resultfor SQLite3.Andrew Kane
-
Raise
ActiveRecord::ReadOnlyErrorwhen pessimistically locking with a readonly role.Joshua Young
-
Fix using the
SQLite3Adapter'sdbconsolemethod outside of a Rails application.Hartley McGuire
-
Fix migrating multiple databases with
ActiveRecord::PendingMigrationaction.Gannon McGibbon
-
Enable automatically retrying idempotent association queries on connection errors.
Hartley McGuire
-
Add
allow_retrytosql.active_recordinstrumentation.This enables identifying queries which queries are automatically retryable on connection errors.
Hartley McGuire
-
Better support UPDATE with JOIN for Postgresql and SQLite3
Previously when generating update queries with one or more JOIN clauses, Active Record would use a sub query which would prevent to reference the joined tables in the
SETclause, for instance:Comment.joins(:post).update_all("title = posts.title")This is now supported as long as the relation doesn't also use a
LIMIT,ORDERorGROUP BYclause. This was supported by the MySQL adapter for a long time.Jean Boussier
-
Introduce a before-fork hook in
ActiveSupport::Testing::Parallelizationto clear existing connections, to avoid fork-safety issues with the mysql2 adapter.Fixes #41776
Mike Dalessio, Donal McBreen
-
PoolConfig no longer keeps a reference to the connection class.
Keeping a reference to the class caused subtle issues when combined with reloading in development. Fixes #54343.
Mike Dalessio
-
Fix SQL notifications sometimes not sent when using async queries.
Post.async_count ActiveSupport::Notifications.subscribed(->(*) { "Will never reach here" }) do Post.count endIn rare circumstances and under the right race condition, Active Support notifications would no longer be dispatched after using an asynchronous query. This is now fixed.
Edouard Chin
-
Eliminate queries loading dumped schema cache on Postgres
Improve resiliency by avoiding needing to open a database connection to load the type map while defining attribute methods at boot when a schema cache file is configured on PostgreSQL databases.
James Coleman
-
ActiveRecord::Coder::JSONcan be instantiatedOptions can now be passed to
ActiveRecord::Coder::JSONwhen instantiating the coder. This allows:serialize :config, coder: ActiveRecord::Coder::JSON.new(symbolize_names: true)matthaigh27
-
Deprecate using
insert_all/upsert_allwith unpersisted records in associations.Using these methods on associations containing unpersisted records will now show a deprecation warning, as the unpersisted records will be lost after the operation.
Nick Schwaderer
-
Make column name optional for
index_exists?.This aligns well with
remove_indexsignature as well, where index name doesn't need to be derived from the column names.Ali Ismayiliov
-
Change the payload name of
sql.active_recordnotification for eager loading from "SQL" to "#{model.name} Eager Load".zzak
-
Enable automatically retrying idempotent
#exists?queries on connection errors.Hartley McGuire, classidied
-
Deprecate usage of unsupported methods in conjunction with
update_all:update_allwill now print a deprecation message if a query includes eitherWITH,WITH RECURSIVEorDISTINCTstatements. Those were never supported and were ignored when generating the SQL query.An error will be raised in a future Rails release. This behavior will be consistent with
delete_allwhich currently raises an error for unsupported statements.Edouard Chin
-
The table columns inside
schema.rbare now sorted alphabetically.Previously they'd be sorted by creation order, which can cause merge conflicts when two branches modify the same table concurrently.
John Duff
-
Introduce versions formatter for the schema dumper.
It is now possible to override how schema dumper formats versions information inside the
structure.sqlfile. Currently, the versions are simply sorted in the decreasing order. Within large teams, this can potentially cause many merge conflicts near the top of the list.Now, the custom formatter can be provided with a custom sorting logic (e.g. by hash values of the versions), which can greatly reduce the number of conflicts.
fatkodima
-
Serialized attributes can now be marked as comparable.
A not rare issue when working with serialized attributes is that the serialized representation of an object can change over time. Either because you are migrating from one serializer to the other (e.g. YAML to JSON or to msgpack), or because the serializer used subtly changed its output.
One example is libyaml that used to have some extra trailing whitespaces, and recently fixed that. When this sorts of thing happen, you end up with lots of records that report being changed even though they aren't, which in the best case leads to a lot more writes to the database and in the worst case lead to nasty bugs.
The solution is to instead compare the deserialized representation of the object, however Active Record can't assume the deserialized object has a working
==method. Hence why this new functionality is opt-in.serialize :config, type: Hash, coder: JSON, comparable: trueJean Boussier
-
Fix MySQL default functions getting dropped when changing a column's nullability.
Bastian Bartmann
-
SQLite extensions can be configured in
config/database.yml.The database configuration option
extensions:allows an application to load SQLite extensions when usingsqlite3>= v2.4.0. The array members may be filesystem paths or the names of modules that respond to.to_path:development: adapter: sqlite3 extensions: - SQLean::UUID # module name responding to `.to_path` - .sqlpkg/nalgeon/crypto/crypto.so # or a filesystem path - <%= AppExtensions.location %> # or ruby code returning a pathMike Dalessio
-
ActiveRecord::Middleware::ShardSelectorsupports granular database connection switching.A new configuration option,
class_name:, is introduced toconfig.active_record.shard_selectorto allow an application to specify the abstract connection class to be switched by the shard selection middleware. The default class isActiveRecord::Base.For example, this configuration tells
ShardSelectorto switch shards usingAnimalsRecord.connected_to:config.active_record.shard_selector = { class_name: "AnimalsRecord" }Mike Dalessio
-
Reset relations after
insert_all/upsert_all.Bulk insert/upsert methods will now call
resetif used on a relation, matching the behavior ofupdate_all.Milo Winningham
-
Use
_Nas a parallel tests databases suffixesPeviously,
-Nwas used as a suffix. This can cause problems for RDBMSes which do not support dashes in database names.fatkodima
-
Remember when a database connection has recently been verified (for two seconds, by default), to avoid repeated reverifications during a single request.
This should recreate a similar rate of verification as in Rails 7.1, where connections are leased for the duration of a request, and thus only verified once.
Matthew Draper
-
Allow to reset cache counters for multiple records.
Aircraft.reset_counters([1, 2, 3], :wheels_count)It produces much fewer queries compared to the custom implementation using looping over ids. Previously:
O(ids.size * counters.size)queries, now:O(ids.size + counters.size)queries.fatkodima
-
Add
affected_rowstosql.active_recordNotification.Hartley McGuire
-
Fix
sumwhen performing a grouped calculation.User.group(:friendly).sumno longer worked. This is fixed.Edouard Chin
-
Add support for enabling or disabling transactional tests per database.
A test class can now override the default
use_transactional_testssetting for individual databases, which can be useful if some databases need their current state to be accessible to an external process while tests are running.class MostlyTransactionalTest < ActiveSupport::TestCase self.use_transactional_tests = true skip_transactional_tests_for_database :shared endMatthew Cheetham, Morgan Mareve
-
Cast
query_cachevalue when using URL configuration.zzak
-
NULLS NOT DISTINCT works with UNIQUE CONSTRAINT as well as UNIQUE INDEX.
Ryuta Kamizono
-
PG::UnableToSend: no connection to the serveris now retryable as a connection-related exceptionKazuma Watanabe
Action View
-
The BEGIN template annotation/comment was previously printed on the same line as the following element. We now insert a newline inside the comment so it spans two lines without adding visible whitespace to the HTML output to enhance readability.
Before:
<!-- BEGIN /Users/siaw23/Desktop/rails/actionview/test/fixtures/actionpack/test/greeting.html.erb --><p>This is grand!</p>After:
<!-- BEGIN /Users/siaw23/Desktop/rails/actionview/test/fixtures/actionpack/test/greeting.html.erb --><p>This is grand!</p>Emmanuel Hayford
-
Add structured events for Action View:
action_view.render_templateaction_view.render_partialaction_view.render_layoutaction_view.render_collectionaction_view.render_start
Gannon McGibbon
-
Fix label with
foroption not getting prefixed by formnamespacevalueAbeid Ahmed, Hartley McGuire
-
Add
fetchpriorityto Link headers to match HTML generated bypreload_link_tag.Guillermo Iguaran
-
Add CSP
nonceto Link headers generated bypreload_link_tag.Alexander Gitter
-
Allow
current_page?to match against specific HTTP method(s) with amethod:option.Ben Sheldon
-
Remove
autocomplete="off"on hidden inputs generated by the following tags:form_tag,token_tag,method_tag
As well as the hidden parameter fields included in
button_to,check_box,select(withmultiple) andfile_fieldforms.nkulway
-
Enable configuring the strategy for tracking dependencies between Action View templates.
The existing
:regexstrategy is kept as the default, but withload_defaults 8.1the strategy will be:ruby(using a real Ruby parser).Hartley McGuire
-
Introduce
relative_time_in_wordshelperrelative_time_in_words(3.minutes.from_now) # => "in 3 minutes" relative_time_in_words(3.minutes.ago) # => "3 minutes ago" relative_time_in_words(10.seconds.ago, include_seconds: true) # => "less than 10 seconds ago"Matheus Richard
-
Make
nonce: falseremove the nonce attribute fromjavascript_tag,javascript_include_tag, andstylesheet_link_tag.francktrouillez
-
Add
dom_targethelper to createdom_id-like strings from an unlimited number of objects.Ben Sheldon
-
Respect
html_options[:form]whencollection_checkboxesgenerates the hidden<input>.Riccardo Odone
-
Layouts have access to local variables passed to
render.This fixes #31680 which was a regression in Rails 5.1.
Mike Dalessio
-
Argument errors related to strict locals in templates now raise an
ActionView::StrictLocalsError, and all other argument errors are reraised as-is.Previously, any
ArgumentErrorraised during template rendering was swallowed during strict local error handling, so that anArgumentErrorunrelated to strict locals (e.g., a helper method invoked with incorrect arguments) would be replaced by a similarArgumentErrorwith an unrelated backtrace, making it difficult to debug templates.Now, any
ArgumentErrorunrelated to strict locals is reraised, preserving the original backtrace for developers.Also note that
ActionView::StrictLocalsErroris a subclass ofArgumentError, so any existing code that rescuesArgumentErrorwill continue to work.Fixes #52227.
Mike Dalessio
-
Improve error highlighting of multi-line methods in ERB templates or templates where the error occurs within a do-end block.
Martin Emde
-
Fix a crash in ERB template error highlighting when the error occurs on a line in the compiled template that is past the end of the source template.
Martin Emde
-
Improve reliability of ERB template error highlighting. Fix infinite loops and crashes in highlighting and improve tolerance for alternate ERB handlers.
Martin Emde
-
Allow
hidden_fieldandhidden_field_tagto accept a custom autocomplete value.brendon
-
Add a new configuration
content_security_policy_nonce_autofor automatically adding a nonce to the tags affected by the directives specified by thecontent_security_policy_nonce_directivesconfiguration option.francktrouillez
Action Pack
-
Submit test requests using
as: :htmlwithContent-Type: x-www-form-urlencodedSean Doyle
-
Add link-local IP ranges to
ActionDispatch::RemoteIpdefault proxies.Link-local addresses (
169.254.0.0/16for IPv4 andfe80::/10for IPv6) are now included in the default trusted proxy list, similar to private IP ranges.Adam Daniels
-
remote_ipwill no longer ignore IPs in X-Forwarded-For headers if they are accompanied by port information.Duncan Brown, Prevenios Marinos, Masafumi Koba, Adam Daniels
-
Add
action_dispatch.verbose_redirect_logssetting that logs where redirects were called from.Similar to
active_record.verbose_query_logsandactive_job.verbose_enqueue_logs, this adds a line in your logs that shows where a redirect was called from.Example:
Redirected to http://localhost:3000/posts/1 ↳ app/controllers/posts_controller.rb:32:in `block (2 levels) in create'Dennis Paagman
-
Add engine route filtering and better formatting in
bin/rails routes.Allow engine routes to be filterable in the routing inspector, and improve formatting of engine routing output.
Before:
> bin/rails routes -e engine_only No routes were found for this grep pattern. For more information about routes, see the Rails guide: https://guides.rubyonrails.org/routing.html.After:
> bin/rails routes -e engine_only Routes for application: No routes were found for this grep pattern. For more information about routes, see the Rails guide: https://guides.rubyonrails.org/routing.html. Routes for Test::Engine: Prefix Verb URI Pattern Controller#Action engine GET /engine_only(.:format) a#bDennis Paagman, Gannon McGibbon
-
Add structured events for Action Pack and Action Dispatch:
action_dispatch.redirectaction_controller.request_startedaction_controller.request_completedaction_controller.callback_haltedaction_controller.rescue_from_handledaction_controller.file_sentaction_controller.redirectedaction_controller.data_sentaction_controller.unpermitted_parametersaction_controller.fragment_cache
Adrianna Chang
-
URL helpers for engines mounted at the application root handle
SCRIPT_NAMEcorrectly.Fixed an issue where
SCRIPT_NAMEis not applied to paths generated for routes in an engine mounted at "/".Mike Dalessio
-
Update
ActionController::Metal::RateLimitingto support passing method names to:byand:withclass SignupsController < ApplicationController rate_limit to: 10, within: 1.minute, with: :redirect_with_flash private def redirect_with_flash redirect_to root_url, alert: "Too many requests!" end endSean Doyle
-
Optimize
ActionDispatch::Http::URL.build_host_urlwhen protocol is included in host.When using URL helpers with a host that includes the protocol (e.g.,
{ host: "https://example.com" }), skip unnecessary protocol normalization and string duplication since the extracted protocol is already in the correct format. This eliminates 2 string allocations per URL generation and provides a ~10% performance improvement for this case.Joshua Young, Hartley McGuire
-
Allow
action_controller.loggerto be disabled by setting it tonilorfalseinstead of always defaulting toRails.logger.Roberto Miranda
-
Remove deprecated support to a route to multiple paths.
Rafael Mendonça França
-
Remove deprecated support for using semicolons as a query string separator.
Before:
ActionDispatch::QueryParser.each_pair("foo=bar;baz=quux").to_a # => [["foo", "bar"], ["baz", "quux"]]After:
ActionDispatch::QueryParser.each_pair("foo=bar;baz=quux").to_a # => [["foo", "bar;baz=quux"]]Rafael Mendonça França
-
Remove deprecated support to skipping over leading brackets in parameter names in the parameter parser.
Before:
ActionDispatch::ParamBuilder.from_query_string("[foo]=bar") # => { "foo" => "bar" } ActionDispatch::ParamBuilder.from_query_string("[foo][bar]=baz") # => { "foo" => { "bar" => "baz" } }After:
ActionDispatch::ParamBuilder.from_query_string("[foo]=bar") # => { "[foo]" => "bar" } ActionDispatch::ParamBuilder.from_query_string("[foo][bar]=baz") # => { "[foo]" => { "bar" => "baz" } }Rafael Mendonça França
-
Deprecate
Rails.application.config.action_dispatch.ignore_leading_brackets.Rafael Mendonça França
-
Raise
ActionController::TooManyRequestserror fromActionController::RateLimitingRequests that exceed the rate limit raise an
ActionController::TooManyRequestserror. By default, Action Dispatch rescues the error and responds with a429 Too Many Requestsstatus.Sean Doyle
-
Add .md/.markdown as Markdown extensions and add a default
markdown:renderer:class Page def to_markdown body end end class PagesController < ActionController::Base def show @page = Page.find(params[:id]) respond_to do |format| format.html format.md { render markdown: @page } end end endDHH
-
Add headers to engine routes inspection command
Petrik de Heus
-
Add "Copy as text" button to error pages
Mikkel Malmberg
-
Add
scope:option torate_limitmethod.Previously, it was not possible to share a rate limit count between several controllers, since the count was by default separate for each controller.
Now, the
scope:option solves this problem.class APIController < ActionController::API rate_limit to: 2, within: 2.seconds, scope: "api" end class API::PostsController < APIController # ... end class API::UsersController < APIController # ... endArthurPV, Kamil Hanus
-
Add support for
rack.response_finishedcallbacks in ActionDispatch::Executor.The executor middleware now supports deferring completion callbacks to later in the request lifecycle by utilizing Rack's
rack.response_finishedmechanism, when available. This enables applications to definerack.response_finishedcallbacks that may rely on state that would be cleaned up by the executor's completion callbacks.Adrianna Chang, Hartley McGuire
-
Produce a log when
rescue_fromis invoked.Steven Webb, Jean Boussier
-
Allow hosts redirects from
hostsRails configurationconfig.action_controller.allowed_redirect_hosts << "example.com"Kevin Robatel
-
rate_limit.action_controllernotification has additional payloadadditional values: count, to, within, by, name, cache_key
Jonathan Rochkind
-
Add JSON support to the built-in health controller.
The health controller now responds to JSON requests with a structured response containing status and timestamp information. This makes it easier for monitoring tools and load balancers to consume health check data programmatically.
# /up.json { "status": "up", "timestamp": "2025-09-19T12:00:00Z" }Francesco Loreti, Juan Vásquez
-
Allow to open source file with a crash from the browser.
Igor Kasyanchuk
-
Always check query string keys for valid encoding just like values are checked.
Casper Smits
-
Always return empty body for HEAD requests in
PublicExceptionsandDebugExceptions.This is required by
Rack::Lint(per RFC9110).Hartley McGuire
-
Add comprehensive support for HTTP Cache-Control request directives according to RFC 9111.
Provides a
request.cache_control_directivesobject that gives access to request cache directives:# Boolean directives request.cache_control_directives.only_if_cached? # => true/false request.cache_control_directives.no_cache? # => true/false request.cache_control_directives.no_store? # => true/false request.cache_control_directives.no_transform? # => true/false # Value directives request.cache_control_directives.max_age # => integer or nil request.cache_control_directives.max_stale # => integer or nil (or true for valueless max-stale) request.cache_control_directives.min_fresh # => integer or nil request.cache_control_directives.stale_if_error # => integer or nil # Special helpers for max-stale request.cache_control_directives.max_stale? # => true if max-stale present (with or without value) request.cache_control_directives.max_stale_unlimited? # => true only for valueless max-staleExample usage:
def show if request.cache_control_directives.only_if_cached? @article = Article.find_cached(params[:id]) return head(:gateway_timeout) if @article.nil? else @article = Article.find(params[:id]) end render :show endegg528
-
Add assert_in_body/assert_not_in_body as the simplest way to check if a piece of text is in the response body.
DHH
-
Include cookie name when calculating maximum allowed size.
Hartley McGuire
-
Implement
must-understanddirective according to RFC 9111.The
must-understanddirective indicates that a cache must understand the semantics of the response status code, or discard the response. This directive is enforced to be used only withno-storeto ensure proper cache behavior.class ArticlesController < ApplicationController def show @article = Article.find(params[:id]) if @article.special_format? must_understand render status: 203 # Non-Authoritative Information else fresh_when @article end end endheka1024
-
The JSON renderer doesn't escape HTML entities or Unicode line separators anymore.
Using
render json:will no longer escape<,>,&,U+2028andU+2029characters that can cause errors when the resulting JSON is embedded in JavaScript, or vulnerabilities when the resulting JSON is embedded in HTML.Since the renderer is used to return a JSON document as
application/json, it's typically not necessary to escape those characters, and it improves performance.Escaping will still occur when the
:callbackoption is set, since the JSON is used as JavaScript code in this situation (JSONP).You can use the
:escapeoption or setconfig.action_controller.escape_json_responsestotrueto restore the escaping behavior.class PostsController < ApplicationController def index render json: Post.last(30), escape: true end endÉtienne Barrié, Jean Boussier
-
Load lazy route sets before inserting test routes
Without loading lazy route sets early, we miss
after_routes_loadedcallbacks, or risk invoking them with the test routes instead of the real ones if another load is triggered by an engine.Gannon McGibbon
-
Raise
AbstractController::DoubleRenderErrorifheadis called after rendering.After this change, invoking
headwill lead to an error if response body is already set:class PostController < ApplicationController def index render locals: {} head :ok end endIaroslav Kurbatov
-
The Cookie Serializer can now serialize an Active Support SafeBuffer when using message pack.
Such code would previously produce an error if an application was using messagepack as its cookie serializer.
class PostController < ApplicationController def index flash.notice = t(:hello_html) # This would try to serialize a SafeBuffer, which was not possible. end endEdouard Chin
-
Fix
Rails.application.reload_routes!from clearing almost all routes.When calling
Rails.application.reload_routes!inside a middleware of a Rake task, it was possible under certain conditions that all routes would be cleared. If ran inside a middleware, this would result in getting a 404 on most page you visit. This issue was only happening in development.Edouard Chin
-
Add resource name to the
ArgumentErrorthat's raised when invalid:onlyor:exceptoptions are given to#resourceor#resourcesThis makes it easier to locate the source of the problem, especially for routes drawn by gems.
Before:
:only and :except must include only [:index, :create, :new, :show, :update, :destroy, :edit], but also included [:foo, :bar]After:
Route `resources :products` - :only and :except must include only [:index, :create, :new, :show, :update, :destroy, :edit], but also included [:foo, :bar]Jeremy Green
-
A route pointing to a non-existing controller now returns a 500 instead of a 404.
A controller not existing isn't a routing error that should result in a 404, but a programming error that should result in a 500 and be reported.
Until recently, this was hard to untangle because of the support for dynamic
:controllersegment in routes, but since this is deprecated and will be removed in Rails 8.1, we can now easily not consider missing controllers as routing errors.Jean Boussier
-
Add
check_collisionsoption toActionDispatch::Session::CacheStore.Newly generated session ids use 128 bits of randomness, which is more than enough to ensure collisions can't happen, but if you need to harden sessions even more, you can enable this option to check in the session store that the id is indeed free you can enable that option. This however incurs an extra write on session creation.
Shia
-
In ExceptionWrapper, match backtrace lines with built templates more often, allowing improved highlighting of errors within do-end blocks in templates. Fix for Ruby 3.4 to match new method labels in backtrace.
Martin Emde
-
Allow setting content type with a symbol of the Mime type.
# Before response.content_type = "text/html" # After response.content_type = :htmlPetrik de Heus
Active Job
-
Add structured events for Active Job:
active_job.enqueuedactive_job.bulk_enqueuedactive_job.startedactive_job.completedactive_job.retry_scheduledactive_job.retry_stoppedactive_job.discardedactive_job.interruptactive_job.resumeactive_job.step_skippedactive_job.step_startedactive_job.step
Adrianna Chang
-
Deprecate built-in
sidekiqadapter.If you're using this adapter, upgrade to
sidekiq7.3.3 or later to use thesidekiqgem's adapter.fatkodima
-
Remove deprecated internal
SuckerPunchadapter in favor of the adapter included with thesucker_punchgem.Rafael Mendonça França
-
Remove support to set
ActiveJob::Base.enqueue_after_transaction_committo:never,:alwaysand:default.Rafael Mendonça França
-
Remove deprecated
Rails.application.config.active_job.enqueue_after_transaction_commit.Rafael Mendonça França
-
ActiveJob::Serializers::ObjectSerializers#klassmethod is now public.Custom Active Job serializers must have a public
#klassmethod too. The returned class will be index allowing for faster serialization.Jean Boussier
-
Allow jobs to the interrupted and resumed with Continuations
A job can use Continuations by including the
ActiveJob::Continuableconcern. Continuations split jobs into steps. When the queuing system is shutting down jobs can be interrupted and their progress saved.class ProcessImportJob include ActiveJob::Continuable def perform(import_id) @import = Import.find(import_id) # block format step :initialize do @import.initialize end # step with cursor, the cursor is saved when the job is interrupted step :process do |step| @import.records.find_each(start: step.cursor) do |record| record.process step.advance! from: record.id end end # method format step :finalize private def finalize @import.finalize end end endDonal McBreen
-
Defer invocation of ActiveJob enqueue callbacks until after commit when
enqueue_after_transaction_commitis enabled.Will Roever
-
Add
report:option toActiveJob::Base#retry_onand#discard_onWhen the
report:option is passed, errors will be reported to the error reporter before being retried / discarded.Andrew Novoselac
-
Accept a block for
ActiveJob::ConfiguredJob#perform_later.This was inconsistent with a regular
ActiveJob::Base#perform_later.fatkodima
-
Raise a more specific error during deserialization when a previously serialized job class is now unknown.
ActiveJob::UnknownJobClassErrorwill be raised instead of a more genericNameErrorto make it easily possible for adapters to tell if theNameErrorwas raised during job execution or deserialization.Earlopain
Action Mailer
-
Add structured events for Action Mailer:
action_mailer.deliveredaction_mailer.processed
Gannon McGibbon
-
Add
deliver_all_laterto enqueue multiple emails at once.user_emails = User.all.map { |user| Notifier.welcome(user) } ActionMailer.deliver_all_later(user_emails) # use a custom queue ActionMailer.deliver_all_later(user_emails, queue: :my_queue)This can greatly reduce the number of round-trips to the queue datastore. For queue adapters that do not implement the
enqueue_allmethod, we fall back to enqueuing email jobs indvidually.fatkodima
Action Cable
-
Allow passing composite channels to
ActionCable::Channel#stream_for– e.g.stream_for [ group, group.owner ]hey-leon
-
Allow setting nil as subscription connection identifier for Redis.
Nguyen Nguyen
Active Storage
-
Add structured events for Active Storage:
active_storage.service_uploadactive_storage.service_downloadactive_storage.service_streaming_downloadactive_storage.previewactive_storage.service_deleteactive_storage.service_delete_prefixedactive_storage.service_existactive_storage.service_urlactive_storage.service_mirror
Gannon McGibbon
-
Allow analyzers and variant transformer to be fully configurable
# ActiveStorage.analyzers can be set to an empty array: config.active_storage.analyzers = [] # => ActiveStorage.analyzers = [] # or use custom analyzer: config.active_storage.analyzers = [ CustomAnalyzer ] # => ActiveStorage.analyzers = [ CustomAnalyzer ]If no configuration is provided, it will use the default analyzers.
You can also disable variant processor to remove warnings on startup about missing gems.
config.active_storage.variant_processor = :disabledzzak, Alexandre Ruban
-
Remove deprecated
:azurestorage service.Rafael Mendonça França
-
Remove unnecessary calls to the GCP metadata server.
Calling Google::Auth.get_application_default triggers an explicit call to the metadata server - given it was being called for significant number of file operations, it can lead to considerable tail latencies and even metadata server overloads. Instead, it's preferable (and significantly more efficient) that applications use:
Google::Apis::RequestOptions.default.authorization = Google::Auth.get_application_default(...)In the cases applications do not set that, the GCP libraries automatically determine credentials.
This also enables using credentials other than those of the associated GCP service account like when using impersonation.
Alex Coomans
-
Direct upload progress accounts for server processing time.
Jeremy Daer
-
Delegate
ActiveStorage::Filename#to_strto#to_sSupports checking String equality:
filename = ActiveStorage::Filename.new("file.txt") filename == "file.txt" # => true filename in "file.txt" # => true "file.txt" == filename # => trueSean Doyle
-
A Blob will no longer autosave associated Attachment.
This fixes an issue where a record with an attachment would have its dirty attributes reset, preventing your
after commitcallbacks on that record to behave as expected.Note that this change doesn't require any changes on your application and is supposed to be internal. Active Storage Attachment will continue to be autosaved (through a different relation).
Edouard-chin
Action Mailbox
-
Add
reply_to_addressextension method onMail::Message.Mr0grog
Action Text
-
De-couple
@rails/actiontext/attachment_upload.jsfromTrix.AttachmentImplement
@rails/actiontext/index.jswith adirect-upload:progressevent listeners andPromiseresolution.Sean Doyle
-
Capture block content for form helper methods
<%= rich_textarea_tag :content, nil do %> <h1>hello world</h1> <% end %> <!-- <input type="hidden" name="content" id="trix_input_1" value="<h1>hello world</h1>"/><trix-editor … --> <%= rich_textarea :message, :content, input: "trix_input_1" do %> <h1>hello world</h1> <% end %> <!-- <input type="hidden" name="message[content]" id="trix_input_1" value="<h1>hello world</h1>"/><trix-editor … --> <%= form_with model: Message.new do |form| %> <%= form.rich_textarea :content do %> <h1>hello world</h1> <% end %> <% end %> <!-- <form action="/messages" accept-charset="UTF-8" method="post"><input type="hidden" name="message[content]" id="message_content_trix_input_message" value="<h1>hello world</h1>"/><trix-editor … -->Sean Doyle
-
Generalize
:rich_text_areaCapybara selectorPrepare for more Action Text-capable WYSIWYG editors by making
:rich_text_arearely on the presence of[role="textbox"]and[contenteditable]HTML attributes rather than a<trix-editor>element.Sean Doyle
-
Forward
fill_in_rich_text_areaoptions to Capybarafill_in_rich_textarea "Rich text editor", id: "trix_editor_1", with: "Hello world!"Sean Doyle
-
Attachment upload progress accounts for server processing time.
Jeremy Daer
-
The Trix dependency is now satisfied by a gem,
action_text-trix, rather than vendored files. This allows applications to bump Trix versions independently of Rails releases. Effectively this also upgrades Trix to>= 2.1.15.Mike Dalessio
-
Change
ActionText::RichText#embedsassignment frombefore_savetobefore_validationSean Doyle
Railties
-
Suggest
bin/rails action_text:installfrom Action Dispatch error pageSean Doyle
-
Remove deprecated
STATS_DIRECTORIES.Rafael Mendonça França
-
Remove deprecated
bin/rake statscommand.Rafael Mendonça França
-
Remove deprecated
rails/console/methods.rbfile.Rafael Mendonça França
-
Don't generate system tests by default.
Rails scaffold generator will no longer generate system tests by default. To enable this pass
--system-tests=trueor generate them withbin/rails generate system_test name_of_test.Eileen M. Uchitelle
-
Optionally skip bundler-audit.
Skips adding the
bin/bundler-audit&config/bundler-audit.ymlif the gem is not installed whenbin/rails app:updateruns.Passes an option to
--skip-bundler-auditwhen new apps are generated & adds that same option to the--minimalgenerator flag.Jill Klang
-
Show engine routes in
/rails/info/routesas well.Petrik de Heus
-
Exclude
asset_pathconfiguration from Kamaldeploy.ymlfor API applications.API applications don't serve assets, so the
asset_pathconfiguration indeploy.ymlis not needed and can cause 404 errors on in-flight requests. The asset_path is now only included for regular Rails applications that serve assets.Saiqul Haq
-
Reverted the incorrect default
config.public_file_server.headersconfig.If you created a new application using Rails
8.1.0.beta1, make sure to regenerateconfig/environments/production.rb, or to manually edit theconfig.public_file_server.headersconfiguration to just be:# Cache assets for far-future expiry since they are all digest stamped. config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" }Jean Boussier
-
Add command
rails credentials:fetch PATHto get the value of a credential from the credentials file.$ bin/rails credentials:fetch kamal_registry.passwordMatthew Nguyen, Jean Boussier
-
Generate static BCrypt password digests in fixtures instead of dynamic ERB expressions.
Previously, fixtures with password digest attributes used
<%= BCrypt::Password.create("secret") %>, which regenerated the hash on each test run. Now generates a static hash with a comment showing how to recreate it.Nate Smith, Cassia Scheffer
-
Broaden the
.gitignoreentry when adding a credentials key to ignore all key files.Greg Molnar
-
Remove unnecessary
ruby-versioninput fromruby/setup-rubyTangRufus
-
Add --reset option to bin/setup which will call db:reset as part of the setup.
DHH
-
Add RuboCop cache restoration to RuboCop job in GitHub Actions workflow templates.
Lovro Bikić
-
Skip generating mailer-related files in authentication generator if the application does not use ActionMailer
Rami Massoud
-
Introduce
bin/cifor running your tests, style checks, and security audits locally or in the cloud.The specific steps are defined by a new DSL in
config/ci.rb.ActiveSupport::ContinuousIntegration.run do step "Setup", "bin/setup --skip-server" step "Style: Ruby", "bin/rubocop" step "Security: Gem audit", "bin/bundler-audit" step "Tests: Rails", "bin/rails test test:system" endOptionally use gh-signoff to set a green PR status - ready for merge.
Jeremy Daer, DHH
-
Generate session controller tests when running the authentication generator.
Jerome Dalbert
-
Add bin/bundler-audit and config/bundler-audit.yml for discovering and managing known security problems with app gems.
DHH
-
Rails no longer generates a
bin/bundlebinstub when creating new applications.The
bin/bundlebinstub used to help activate the right version of bundler. This is no longer necessary as this mechanism is now part of Rubygem itself.Edouard Chin
-
Add a
SessionTestHelpermodule withsign_in_as(user)andsign_outtest helpers when runningrails g authentication. Simplifies authentication in integration tests.Bijan Rahnema
-
Rate limit password resets in authentication generator
This helps mitigate abuse from attackers spamming the password reset form.
Chris Oliver
-
Update
rails new --minimaloptionExtend the
--minimalflag to exclude recently added features:skip_brakeman,skip_ci,skip_docker,skip_kamal,skip_rubocop,skip_solidandskip_thruster.eelcoj
-
Add
application-namemetadata to application layoutThe following metatag will be added to
app/views/layouts/application.html.erb<meta name="application-name" content="Name of Rails Application">Steve Polito
-
Use
secret_key_basefrom ENV or credentials when present locally.When ENV["SECRET_KEY_BASE"] or
Rails.application.credentials.secret_key_baseis set for test or development, it is used for theRails.config.secret_key_base, instead of generating atmp/local_secret.txtfile.Petrik de Heus
-
Introduce
RAILS_MASTER_KEYplaceholder in generated ci.yml filesSteve Polito
-
Colorize the Rails console prompt even on non standard environments.
Lorenzo Zabot
-
Don't enable YJIT in development and test environments
Development and test environments tend to reload code and redefine methods (e.g. mocking), hence YJIT isn't generally faster in these environments.
Ali Ismayilov, Jean Boussier
-
Only include PermissionsPolicy::Middleware if policy is configured.
Petrik de Heus
Guides
-
In the Active Job bug report template set the queue adapter to the test adapter so that
assert_enqueued_withcan pass.Andrew White
-
Ensure all bug report templates set
config.secret_key_baseto avoid generation oftmp/local_secret.txtfiles when running the report template.Andrew White
Active Support
-
Fix
Enumerable#soleto return the full tuple instead of just the first element of the tuple.Olivier Bellone
-
Fix parallel tests hanging when worker processes die abruptly.
Previously, if a worker process was killed (e.g., OOM killed,
kill -9) during parallel test execution, the test suite would hang forever waiting for the dead worker.Joshua Young
-
Fix
NameErrorwhenclass_attributeis defined on instance singleton classes.Previously, calling
class_attributeon an instance's singleton class would raise aNameErrorwhen accessing the attribute through the instance.object = MyClass.new object.singleton_class.class_attribute :foo, default: "bar" object.foo # previously raised NameError, now returns "bar"Joshua Young
Active Model
- No changes.
Active Record
-
Fix SQLite3 data loss during table alterations with CASCADE foreign keys.
When altering a table in SQLite3 that is referenced by child tables with
ON DELETE CASCADEforeign keys, ActiveRecord would silently delete all data from the child tables. This occurred because SQLite requires table recreation for schema changes, and during this process the original table is temporarily dropped, triggering CASCADE deletes on child tables.The root cause was incorrect ordering of operations. The original code wrapped
disable_referential_integrityinside a transaction, butPRAGMA foreign_keyscannot be modified inside a transaction in SQLite - attempting to do so simply has no effect. This meant foreign keys remained enabled during table recreation, causing CASCADE deletes to fire.The fix reverses the order to follow the official SQLite 12-step ALTER TABLE procedure:
disable_referential_integritynow wraps the transaction instead of being wrapped by it. This ensures foreign keys are properly disabled before the transaction starts and re-enabled after it commits, preventing CASCADE deletes while maintaining data integrity through atomic transactions.Ruy Rocha
-
Add support for bound SQL literals in CTEs.
Nicolas Bachschmidt
-
Fix
belongs_toassociations not to clear the entire composite primary key.When clearing a
belongs_toassociation that references a model with composite primary key, only the optional part of the key should be cleared.zzak
-
Fix invalid records being autosaved when distantly associated records are marked for deletion.
Ian Terrell, axlekb AB
Action View
-
Restore
add_default_name_and_idmethod.Hartley McGuire
Action Pack
-
Submit test requests using
as: :htmlwithContent-Type: x-www-form-urlencodedSean Doyle
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Guides
- No changes.
Active Support
-
ActiveSupport::FileUpdateCheckerdoes not depend onTime.nowto prevent unnecessary reloads with time travel test helpersJan Grodowski
-
Fix
ActiveSupport::BroadcastLoggerfrom executing a block argument for each logger (tagged, info, etc.).Jared Armstrong
-
Make
ActiveSupport::Logger#freeze-friendly.Joshua Young
-
Fix
ActiveSupport::HashWithIndifferentAccess#transform_keys!removing defaults.Hartley McGuire
-
Fix
ActiveSupport::HashWithIndifferentAccess#tranform_keys!to handle collisions.If the transformation would result in a key equal to another not yet transformed one, it would result in keys being lost.
Before:
>> {a: 1, b: 2}.with_indifferent_access.transform_keys!(&:succ) => {"c" => 1}After:
>> {a: 1, b: 2}.with_indifferent_access.transform_keys!(&:succ) => {"c" => 1, "d" => 2}Jason T Johnson, Jean Boussier
-
Fix
ActiveSupport::Cache::MemCacheStore#read_multito handle network errors.This method specifically wasn't handling network errors like other codepaths.
Alessandro Dal Grande
-
Fix configuring
RedisCacheStorewithraw: true.fatkodima
-
Fix
Enumerable#solefor infinite collections.fatkodima
Active Model
-
Fix
has_secure_passwordto perform confirmation validation of the password even when blank.The validation was incorrectly skipped when the password only contained whitespace characters.
Fabio Sangiovanni
Active Record
-
Fix query cache for pinned connections in multi threaded transactional tests
When a pinned connection is used across separate threads, they now use a separate cache store for each thread.
This improve accuracy of system tests, and any test using multiple threads.
Heinrich Lee Yu, Jean Boussier
-
Don't add
id_valueattribute alias when attribute/column with that name already exists.Rob Lewis
-
Fix false positive change detection involving STI and polymorphic has one relationships.
Polymorphic
has_onerelationships would always be considered changed when defined in a STI child class, causing nedless extra autosaves.David Fritsch
-
Skip calling
PG::Connection#cancelincancel_any_running_querywhen using libpq >= 18 with pg < 1.6.0, due to incompatibility. Rollback still runs, but may take longer.Yasuo Honda, Lars Kanis
-
Fix stale association detection for polymorphic
belongs_to.Florent Beaurain, Thomas Crambert
-
Fix removal of PostgreSQL version comments in
structure.sqlfor latest PostgreSQL versions which include\restrictBrendan Weibrecht
-
Allow setting
schema_formatin database configuration.primary: schema_format: rubyUseful in multi-database setups to have different formats per-database.
T S Vallender
-
Use ntuples to populate row_count instead of count for Postgres
Jonathan Calvert
-
Fix
#mergewith#oror#andand a mixture of attributes and SQL strings resulting in an incorrect query.base = Comment.joins(:post).where(user_id: 1).where("recent = 1") puts base.merge(base.where(draft: true).or(Post.where(archived: true))).to_sqlBefore:
SELECT "comments".* FROM "comments"
INNER JOIN "posts" ON "posts"."id" = "comments"."post_id"
WHERE (recent = 1)
AND (
"comments"."user_id" = 1
AND (recent = 1)
AND "comments"."draft" = 1
OR "posts"."archived" = 1
)
```
After:
```sql
SELECT "comments".* FROM "comments"
INNER JOIN "posts" ON "posts"."id" = "comments"."post_id"
WHERE "comments"."user_id" = 1
AND (recent = 1)
AND (
"comments"."user_id" = 1
AND (recent = 1)
AND "comments"."draft" = 1
OR "posts"."archived" = 1
)
```
*Joshua Young*
* Fix inline `has_and_belongs_to_many` fixtures for tables with composite primary keys.
*fatkodima*
* Fix migration log message for down operations.
*Bernardo Barreto*
* Prepend `extra_flags` in postgres' `structure_load`
When specifying `structure_load_flags` with a postgres adapter, the flags
were appended to the default flags, instead of prepended.
This caused issues with flags not being taken into account by postgres.
*Alice Loeser*
* Fix `annotate` comments to propagate to `update_all`/`delete_all`.
*fatkodima*
* Fix checking whether an unpersisted record is `include?`d in a strictly
loaded `has_and_belongs_to_many` association.
*Hartley McGuire*
* `create_or_find_by` will now correctly rollback a transaction.
When using `create_or_find_by`, raising a ActiveRecord::Rollback error
in a `after_save` callback had no effect, the transaction was committed
and a record created.
*Edouard Chin*
* Gracefully handle `Timeout.timeout` firing during connection configuration.
Use of `Timeout.timeout` could result in improperly initialized database connection.
This could lead to a partially configured connection being used, resulting in various exceptions,
the most common being with the PostgreSQLAdapter raising `undefined method 'key?' for nil`
or `TypeError: wrong argument type nil (expected PG::TypeMap)`.
*Jean Boussier*
* Fix stale state for composite foreign keys in belongs_to associations.
*Varun Sharma*
## Action View
* Fix label with `for` option not getting prefixed by form `namespace` value
*Abeid Ahmed*, *Hartley McGuire*
* Fix `javascript_include_tag` `type` option to accept either strings and symbols.
```ruby
javascript_include_tag "application", type: :module
javascript_include_tag "application", type: "module"
```
Previously, only the string value was recognized.
*Jean Boussier*
* Fix `excerpt` helper with non-whitespace separator.
*Jonathan Hefner*
## Action Pack
* URL helpers for engines mounted at the application root handle `SCRIPT_NAME` correctly.
Fixed an issue where `SCRIPT_NAME` is not applied to paths generated for routes in an engine
mounted at "/".
*Mike Dalessio*
* Fix `Rails.application.reload_routes!` from clearing almost all routes.
When calling `Rails.application.reload_routes!` inside a middleware of
a Rake task, it was possible under certain conditions that all routes would be cleared.
If ran inside a middleware, this would result in getting a 404 on most page you visit.
This issue was only happening in development.
*Edouard Chin*
* Address `rack 3.2` deprecations warnings.
```
warning: Status code :unprocessable_entity is deprecated and will be removed in a future version of Rack.
Please use :unprocessable_content instead.
```
Rails API will transparently convert one into the other for the foreseeable future.
*Earlopain*, *Jean Boussier*
* Support hash-source in Content Security Policy.
*madogiwa*
* Always return empty body for HEAD requests in `PublicExceptions` and
`DebugExceptions`.
This is required by `Rack::Lint` (per RFC9110).
*Hartley McGuire*
## Active Job
* Include the actual Active Job locale when serializing rather than I18n locale.
*Adrien S*
* Fix `retry_job` instrumentation when using `:test` adapter for Active Job.
*fatkodima*
## Action Mailer
* No changes.
## Action Cable
* Fixed compatibility with `redis` gem `5.4.1`
*Jean Boussier*
* Fixed a possible race condition in `stream_from`.
*OuYangJinTing*
## Active Storage
* Address deprecation of `Aws::S3::Object#upload_stream` in `ActiveStorage::Service::S3Service`.
*Joshua Young*
* Fix `config.active_storage.touch_attachment_records` to work with eager loading.
*fatkodima*
## Action Mailbox
* No changes.
## Action Text
* Add rollup-plugin-terser as a dev dependency.
*Édouard Chin*
## Railties
* Fix `polymorphic_url` and `polymorphic_path` not working when routes are not loaded.
*Édouard Chin*
* Fix Rails console to not override user defined IRB_NAME.
Only change the prompt name if it hasn't been customized in `.irbrc`.
*Jarrett Lusso*
## Guides
* No changes.
Active Support
-
Fix setting
to_time_preserves_timezonefromnew_framework_defaults_8_0.rb.fatkodima
-
Fix Active Support Cache
fetch_multiwhen local store is active.fetch_multinow properly yield to the provided block for missing entries that have been recorded as such in the local store.Jean Boussier
-
Fix execution wrapping to report all exceptions, including
Exception.If a more serious error like
SystemStackErrororNoMemoryErrorhappens, the error reporter should be able to report these kinds of exceptions.Gannon McGibbon
-
Fix
RedisCacheStoreandMemCacheStoreto also handle connection pool related errors.These errors are rescued and reported to
Rails.error.Jean Boussier
-
Fix
ActiveSupport::Cache#read_multito respect version expiry when using local cache.zzak
-
Fix
ActiveSupport::MessageVerifierandActiveSupport::MessageEncryptorconfiguration ofon_rotationcallback.verifier.rotate(old_secret).on_rotation { ... }Now both work as documented.
Jean Boussier
-
Fix
ActiveSupport::MessageVerifierto always be able to verify both URL-safe and URL-unsafe payloads.This is to allow transitioning seemlessly from either configuration without immediately invalidating all previously generated signed messages.
Jean Boussier, Florent Beaurain, Ali Sepehri
-
Fix
cache.fetchto honor the provided expiry when:race_condition_ttlis used.cache.fetch("key", expires_in: 1.hour, race_condition_ttl: 5.second) do "something" endIn the above example, the final cache entry would have a 10 seconds TTL instead of the requested 1 hour.
Dhia
-
Better handle procs with splat arguments in
set_callback.Radamés Roriz
-
Fix
String#mb_charsto not mutate the receiver.Previously it would call
force_encodingon the receiver, now it dups the receiver first.Jean Boussier
-
Improve
ErrorSubscriberto also mark error causes as reported.This avoid some cases of errors being reported twice, notably in views because of how errors are wrapped in
ActionView::Template::Error.Jean Boussier
-
Fix
Module#module_parent_nameto return the correct name after the module has been named.When called on an anonymous module, the return value wouldn't change after the module was given a name later by being assigned to a constant.
mod = Module.new mod.module_parent_name # => "Object" MyModule::Something = mod mod.module_parent_name # => "MyModule"Jean Boussier
Active Model
- No changes.
Active Record
-
Fix inverting
rename_enum_valuewhen:from/:toare provided.fatkodima
-
Prevent persisting invalid record.
Edouard Chin
-
Fix inverting
drop_tablewithout options.fatkodima
-
Fix count with group by qualified name on loaded relation.
Ryuta Kamizono
-
Fix
sumwith qualified name on loaded relation.Chris Gunther
-
The SQLite3 adapter quotes non-finite Numeric values like "Infinity" and "NaN".
Mike Dalessio
-
Handle libpq returning a database version of 0 on no/bad connection in
PostgreSQLAdapter.Before, this version would be cached and an error would be raised during connection configuration when comparing it with the minimum required version for the adapter. This meant that the connection could never be successfully configured on subsequent reconnection attempts.
Now, this is treated as a connection failure consistent with libpq, raising a
ActiveRecord::ConnectionFailedand ensuring the version isn't cached, which allows the version to be retrieved on the next connection attempt.Joshua Young, Rian McGuire
-
Fix error handling during connection configuration.
Active Record wasn't properly handling errors during the connection configuration phase. This could lead to a partially configured connection being used, resulting in various exceptions, the most common being with the PostgreSQLAdapter raising
undefined methodkey?' for nilorTypeError: wrong argument type nil (expected PG::TypeMap)`.Jean Boussier
-
Fix a case where a non-retryable query could be marked retryable.
Hartley McGuire
-
Handle circular references when autosaving associations.
zzak
-
PoolConfig no longer keeps a reference to the connection class.
Keeping a reference to the class caused subtle issues when combined with reloading in development. Fixes #54343.
Mike Dalessio
-
Fix SQL notifications sometimes not sent when using async queries.
Post.async_count ActiveSupport::Notifications.subscribed(->(*) { "Will never reach here" }) do Post.count endIn rare circumstances and under the right race condition, Active Support notifications would no longer be dispatched after using an asynchronous query. This is now fixed.
Edouard Chin
-
Fix support for PostgreSQL enum types with commas in their name.
Arthur Hess
-
Fix inserts on MySQL with no RETURNING support for a table with multiple auto populated columns.
Nikita Vasilevsky
-
Fix joining on a scoped association with string joins and bind parameters.
class Instructor < ActiveRecord::Base has_many :instructor_roles, -> { active } end class InstructorRole < ActiveRecord::Base scope :active, -> { joins("JOIN students ON instructor_roles.student_id = students.id") .where(students { status: 1 }) } end Instructor.joins(:instructor_roles).firstThe above example would result in
ActiveRecord::StatementInvalidbecause theactivescope bind parameters would be lost.Jean Boussier
-
Fix a potential race condition with system tests and transactional fixtures.
Sjoerd Lagarde
-
Fix autosave associations to no longer validated unmodified associated records.
Active Record was incorrectly performing validation on associated record that weren't created nor modified as part of the transaction:
Post.create!(author: User.find(1)) # Fail if user is invalidJean Boussier
-
Remember when a database connection has recently been verified (for two seconds, by default), to avoid repeated reverifications during a single request.
This should recreate a similar rate of verification as in Rails 7.1, where connections are leased for the duration of a request, and thus only verified once.
Matthew Draper
Action View
-
Respect
html_options[:form]whencollection_checkboxesgenerates the hidden<input>.Riccardo Odone
-
Layouts have access to local variables passed to
render.This fixes #31680 which was a regression in Rails 5.1.
Mike Dalessio
-
Argument errors related to strict locals in templates now raise an
ActionView::StrictLocalsError, and all other argument errors are reraised as-is.Previously, any
ArgumentErrorraised during template rendering was swallowed during strict local error handling, so that anArgumentErrorunrelated to strict locals (e.g., a helper method invoked with incorrect arguments) would be replaced by a similarArgumentErrorwith an unrelated backtrace, making it difficult to debug templates.Now, any
ArgumentErrorunrelated to strict locals is reraised, preserving the original backtrace for developers.Also note that
ActionView::StrictLocalsErroris a subclass ofArgumentError, so any existing code that rescuesArgumentErrorwill continue to work.Fixes #52227.
Mike Dalessio
-
Fix stack overflow error in dependency tracker when dealing with circular dependencies
Jean Boussier
Action Pack
-
Improve
with_routingtest helper to not rebuild the middleware stack.Otherwise some middleware configuration could be lost.
Édouard Chin
-
Add resource name to the
ArgumentErrorthat's raised when invalid:onlyor:exceptoptions are given to#resourceor#resourcesThis makes it easier to locate the source of the problem, especially for routes drawn by gems.
Before:
:only and :except must include only [:index, :create, :new, :show, :update, :destroy, :edit], but also included [:foo, :bar]After:
Route `resources :products` - :only and :except must include only [:index, :create, :new, :show, :update, :destroy, :edit], but also included [:foo, :bar]Jeremy Green
-
Fix
url_forto handle:path_paramsgracefully when it's not aHash.Prevents various security scanners from causing exceptions.
Martin Emde
-
Fix
ActionDispatch::Executorto unwrap exceptions like other error reporting middlewares.Jean Boussier
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
A Blob will no longer autosave associated Attachment.
This fixes an issue where a record with an attachment would have its dirty attributes reset, preventing your
after commitcallbacks on that record to behave as expected.Note that this change doesn't require any changes on your application and is supposed to be internal. Active Storage Attachment will continue to be autosaved (through a different relation).
Edouard-chin
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Fix Rails console to load routes.
Otherwise
*_pathand*urlmethods are missing on theappobject.Édouard Chin
-
Update
rails new --minimaloptionExtend the
--minimalflag to exclude recently added features:skip_brakeman,skip_ci,skip_docker,skip_kamal,skip_rubocop,skip_solidandskip_thruster.eelcoj
-
Use
secret_key_basefrom ENV or credentials when present locally.When ENV["SECRET_KEY_BASE"] or
Rails.application.credentials.secret_key_baseis set for test or development, it is used for theRails.config.secret_key_base, instead of generating atmp/local_secret.txtfile.Petrik de Heus
Guides
- No changes.
Active Support
-
Fix a bug in
ERB::Util.tokenizethat causes incorrect tokenization when ERB tags are preceeded by multibyte characters.Martin Emde
-
Restore the ability to decorate methods generated by
class_attribute.It always has been complicated to use Module#prepend or an alias method chain to decorate methods defined by
class_attribute, but became even harder in 8.0.This capability is now supported for both reader and writer methods.
Jean Boussier
Active Model
- No changes.
Active Record
-
Fix removing foreign keys with :restrict action for MySQ
fatkodima
-
Fix a race condition in
ActiveRecord::Base#method_missingwhen lazily defining attributes.If multiple thread were concurrently triggering attribute definition on the same model, it could result in a
NoMethodErrorbeing raised.Jean Boussier
-
Fix MySQL default functions getting dropped when changing a column's nullability.
Bastian Bartmann
-
Fix
add_unique_constraint/add_check_constraint/add_foreign_keyto be revertible when given invalid options.fatkodima
-
Fix asynchronous destroying of polymorphic
belongs_toassociations.fatkodima
-
Fix
insert_allto not update existing records.fatkodima
-
NOT VALIDconstraints should not dump increate_table.Ryuta Kamizono
-
Fix finding by nil composite primary key association.
fatkodima
-
Properly reset composite primary key configuration when setting a primary key.
fatkodima
-
Fix Mysql2Adapter support for prepared statements
Using prepared statements with MySQL could result in a
NoMethodErrorexception.Jean Boussier, Leo Arnold, zzak
-
Fix parsing of SQLite foreign key names when they contain non-ASCII characters
Zacharias Knudsen
-
Fix parsing of MySQL 8.0.16+ CHECK constraints when they contain new lines.
Steve Hill
-
Ensure normalized attribute queries use
IS NULLconsistently forniland normalizednilvalues.Joshua Young
-
Fix
sumwhen performing a grouped calculation.User.group(:friendly).sumno longer worked. This is fixed.Edouard Chin
-
Restore back the ability to pass only database name to
DATABASE_URL.fatkodima
Action View
-
Fix a crash in ERB template error highlighting when the error occurs on a line in the compiled template that is past the end of the source template.
Martin Emde
-
Improve reliability of ERB template error highlighting. Fix infinite loops and crashes in highlighting and improve tolerance for alternate ERB handlers.
Martin Emde
Action Pack
-
Add
ActionDispatch::Request::Session#storemethod to conform Rack spec.Yaroslav
Active Job
-
Avoid crashing in Active Job logger when logging enqueueing errors
ActiveJob.perform_all_latercould fail with aTypeErrorwhen all provided jobs failed to be enqueueed.Efstathios Stivaros
Action Mailer
- No changes.
Action Cable
-
Ensure the Postgresql adapter always use a dedicated connection even during system tests.
Fix an issue with the Action Cable Postgresql adapter causing deadlock or various weird pg client error during system tests.
Jean Boussier
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Skip generation system tests related code for CI when
--skip-system-testis given.fatkodima
-
Don't add bin/thrust if thruster is not in Gemfile.
Étienne Barrié
-
Don't install a package for system test when applications don't use it.
y-yagi
Guides
- No changes.
Active Support
-
Remove deprecated support to passing an array of strings to
ActiveSupport::Deprecation#warn.Rafael Mendonça França
-
Remove deprecated support to setting
attr_internal_naming_formatwith a@prefix.Rafael Mendonça França
-
Remove deprecated
ActiveSupport::ProxyObject.Rafael Mendonça França
-
Don't execute i18n watcher on boot. It shouldn't catch any file changes initially, and unnecessarily slows down boot of applications with lots of translations.
Gannon McGibbon, David Stosik
-
Fix
ActiveSupport::HashWithIndifferentAccess#stringify_keysto stringify all keys not just symbols.Previously:
{ 1 => 2 }.with_indifferent_access.stringify_keys[1] # => 2After this change:
{ 1 => 2 }.with_indifferent_access.stringify_keys["1"] # => 2This change can be seen as a bug fix, but since it behaved like this for a very long time, we're deciding to not backport the fix and to make the change in a major release.
Jean Boussier
-
Include options when instrumenting
ActiveSupport::Cache::Store#deleteandActiveSupport::Cache::Store#delete_multi.Adam Renberg Tamm
-
Print test names when running
rails test -vfor parallel tests.John Hawthorn, Abeid Ahmed
-
Deprecate
Benchmark.mscore extension.The
benchmarkgem will become bundled in Ruby 3.5Earlopain
-
ActiveSupport::TimeWithZone#inspectnow uses ISO 8601 style time likeTime#inspectJohn Hawthorn
-
ActiveSupport::ErrorReporter#reportnow assigns a backtrace to unraised exceptions.Previously reporting an un-raised exception would result in an error report without a backtrace. Now it automatically generates one.
Jean Boussier
-
Add
escape_html_entitiesoption toActiveSupport::JSON.encode.This allows for overriding the global configuration found at
ActiveSupport.escape_html_entities_in_jsonfor specific calls toto_json.This should be usable from controllers in the following manner:
class MyController < ApplicationController def index render json: { hello: "world" }, escape_html_entities: false end endNigel Baillie
-
Raise when using key which can't respond to
#to_syminEncryptedConfiguration.As is the case when trying to use an Integer or Float as a key, which is unsupported.
zzak
-
Deprecate addition and since between two
TimeandActiveSupport::TimeWithZone.Previously adding time instances together such as
10.days.ago + 10.days.agoor10.days.ago.since(10.days.ago)produced a nonsensical future date. This behavior is deprecated and will be removed in Rails 8.1.Nick Schwaderer
-
Support rfc2822 format for Time#to_fs & Date#to_fs.
Akshay Birajdar
-
Optimize load time for
Railtie#initialize_i18n. FilterI18n.load_paths passed to the file watcher to only those underRails.root. Previously the watcher would grab all available locales, including those in gems which do not require a watcher because they won't change.Nick Schwaderer
-
Add a
filteroption toin_order_ofto prioritize certain values in the sorting without filtering the results by these values.Igor Depolli
-
Improve error message when using
assert_differenceorassert_changeswith a proc by printing the proc's source code (MRI only).Richard Böhme, Jean Boussier
-
Add a new configuration value
:zoneforActiveSupport.to_time_preserves_timezoneand rename the previoustruevalue to:offset. The new default value is:zone.Jason Kim, John Hawthorn
-
Align instrumentation
payload[:key]in ActiveSupport::Cache to follow the same pattern, with namespaced and normalized keys.Frederik Erbs Spang Thomsen
-
Fix
travel_toto set usec 0 whenwith_usecisfalseand the given argument String or DateTime.mopp
Active Model
-
Add
:except_onoption for validations. Grants the ability to skip validations in specified contexts.class User < ApplicationRecord #... validates :birthday, presence: { except_on: :admin } #... end user = User.new(attributes except birthday) user.save(context: :admin)Drew Bragg
-
Make
ActiveModel::Serialization#read_attribute_for_serializationpublicSean Doyle
-
Add a default token generator for password reset tokens when using
has_secure_password.class User < ApplicationRecord has_secure_password end user = User.create!(name: "david", password: "123", password_confirmation: "123") token = user.password_reset_token User.find_by_password_reset_token(token) # returns user # 16 minutes later... User.find_by_password_reset_token(token) # returns nil # raises ActiveSupport::MessageVerifier::InvalidSignature since the token is expired User.find_by_password_reset_token!(token)DHH
-
Add a load hook
active_model_translationforActiveModel::Translation.Shouichi Kamiya
-
Add
raise_on_missing_translationsoption toActiveModel::Translation. When the option is set,human_attribute_nameraises an error if a translation of the given attribute is missing.# ActiveModel::Translation.raise_on_missing_translations = false Post.human_attribute_name("title") => "Title" # ActiveModel::Translation.raise_on_missing_translations = true Post.human_attribute_name("title") => Translation missing. Options considered were: (I18n::MissingTranslationData) - en.activerecord.attributes.post.title - en.attributes.title raise exception.respond_to?(:to_exception) ? exception.to_exception : exception ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Shouichi Kamiya
-
Introduce
ActiveModel::AttributeAssignment#attribute_writer_missingProvide instances with an opportunity to gracefully handle assigning to an unknown attribute:
class Rectangle include ActiveModel::AttributeAssignment attr_accessor :length, :width def attribute_writer_missing(name, value) Rails.logger.warn "Tried to assign to unknown attribute #{name}" end end rectangle = Rectangle.new rectangle.assign_attributes(height: 10) # => Logs "Tried to assign to unknown attribute 'height'"Sean Doyle
Active Record
-
Fix support for
query_cache: falseindatabase.yml.query_cache: falsewould no longer entirely disable the Active Record query cache.zzak
-
NULLS NOT DISTINCT works with UNIQUE CONSTRAINT as well as UNIQUE INDEX.
Ryuta Kamizono
-
The
db:preparetask no longer loads seeds when a non-primary database is created.Previously, the
db:preparetask would load seeds whenever a new database is created, leading to potential loss of data if a database is added to an existing environment.Introduces a new database config property
seedsto control whether seeds are loaded duringdb:preparewhich defaults totruefor primary database configs andfalseotherwise.Fixes #53348.
Mike Dalessio
-
PG::UnableToSend: no connection to the serveris now retryable as a connection-related exceptionKazuma Watanabe
-
Fix strict loading propagation even if statement cache is not used.
Ryuta Kamizono
-
Allow
rename_enumaccepts two from/to name arguments asrename_tabledoes so.Ryuta Kamizono
-
Remove deprecated support to setting
ENV["SCHEMA_CACHE"].Rafael Mendonça França
-
Remove deprecated support to passing a database name to
cache_dump_filename.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::ConnectionAdapters::ConnectionPool#connection.Rafael Mendonça França
-
Remove deprecated
config.active_record.sqlite3_deprecated_warning.Rafael Mendonça França
-
Remove deprecated
config.active_record.warn_on_records_fetched_greater_than.Rafael Mendonça França
-
Remove deprecated support for defining
enumwith keyword arguments.Rafael Mendonça França
-
Remove deprecated support to finding database adapters that aren't registered to Active Record.
Rafael Mendonça França
-
Remove deprecated
config.active_record.allow_deprecated_singular_associations_name.Rafael Mendonça França
-
Remove deprecated
config.active_record.commit_transaction_on_non_local_return.Rafael Mendonça França
-
Fix incorrect SQL query when passing an empty hash to
ActiveRecord::Base.insert.David Stosik
-
Allow to save records with polymorphic join tables that have
inverse_ofspecified.Markus Doits
-
Fix association scopes applying on the incorrect join when using a polymorphic
has_many through:.Joshua Young
-
Allow
ActiveRecord::Base#pluckto accept hash arguments with symbol and string values.Post.joins(:comments).pluck(:id, comments: :id) Post.joins(:comments).pluck("id", "comments" => "id")Joshua Young
-
Make Float distinguish between
float4andfloat8in PostgreSQL.Fixes #52742
Ryota Kitazawa, Takayuki Nagatomi
-
Allow
drop_tableto accept an array of table names.This will let you to drop multiple tables in a single call.
ActiveRecord::Base.lease_connection.drop_table(:users, :posts)Gabriel Sobrinho
-
Add support for PostgreSQL
IF NOT EXISTSvia the:if_not_existsoption on theadd_enum_valuemethod.Ariel Rzezak
-
When running
db:migrateon a fresh database, load the databases schemas before running migrations.Andrew Novoselac, Marek Kasztelnik
-
Fix an issue where
.left_outer_joinsused with multiple associations that have the same child association but different parents does not join all parents.Previously, using
.left_outer_joinswith the same child association would only join one of the parents.Now it will correctly join both parents.
Fixes #41498.
Garrett Blehm
-
Deprecate
unsigned_floatandunsigned_decimalshort-hand column methods.As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL. Consider using a simple CHECK constraint instead for such columns.
https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
Ryuta Kamizono
-
Drop MySQL 5.5 support.
MySQL 5.5 is the only version that does not support datetime with precision, which we have supported in the core. Now we support MySQL 5.6.4 or later, which is the first version to support datetime with precision.
Ryuta Kamizono
-
Make Active Record asynchronous queries compatible with transactional fixtures.
Previously transactional fixtures would disable asynchronous queries, because transactional fixtures impose all queries use the same connection.
Now asynchronous queries will use the connection pinned by transactional fixtures, and behave much closer to production.
Jean Boussier
-
Deserialize binary data before decrypting
This ensures that we call
PG::Connection.unescape_byteaon PostgreSQL before decryption.Donal McBreen
-
Ensure
ActiveRecord::Encryption.configis always ready before access.Previously,
ActiveRecord::Encryptionconfiguration was deferred untilActiveRecord::Basewas loaded. Therefore, accessingActiveRecord::Encryption.configproperties beforeActiveRecord::Basewas loaded would give incorrect results.ActiveRecord::Encryptionnow has its own loading hook so that its configuration is set as soon as needed.When
ActiveRecord::Baseis loaded, even lazily, it in turn triggers the loading ofActiveRecord::Encryption, thus preserving the original behavior of having its config ready before any use ofActiveRecord::Base.Maxime Réty
-
Add
TimeZoneConverter#==method, so objects will be properly compared by their type, scale, limit & precision.Address #52699.
Ruy Rocha
-
Add support for SQLite3 full-text-search and other virtual tables.
Previously, adding sqlite3 virtual tables messed up
schema.rb.Now, virtual tables can safely be added using
create_virtual_table.Zacharias Knudsen
-
Support use of alternative database interfaces via the
database_cliActiveRecord configuration option.Rails.application.configure do config.active_record.database_cli = { postgresql: "pgcli" } endT S Vallender
-
Add support for dumping table inheritance and native partitioning table definitions for PostgeSQL adapter
Justin Talbott
-
Add support for
ActiveRecord::Pointtype casts usingHashvaluesThis allows
ActiveRecord::Pointto be cast or serialized from a hash with:xand:ykeys of numeric values, mirroring the functionality of existing casts for string and array values. Both string and symbol keys are supported.class PostgresqlPoint < ActiveRecord::Base attribute :x, :point attribute :y, :point attribute :z, :point end val = PostgresqlPoint.new({ x: '(12.34, -43.21)', y: [12.34, '-43.21'], z: {x: '12.34', y: -43.21} }) ActiveRecord::Point.new(12.32, -43.21) == val.x == val.y == val.zStephen Drew
-
Replace
SQLite3::Database#busy_timeoutwith#busy_handler_timeout=.Provides a non-GVL-blocking, fair retry interval busy handler implementation.
Stephen Margheim
-
SQLite3Adapter: Translate
SQLite3::BusyExceptionintoActiveRecord::StatementTimeout.Matthew Nguyen
-
Include schema name in
enable_extensionstatements indb/schema.rb.The schema dumper will now include the schema name in generated
enable_extensionstatements if they differ from the current schema.For example, if you have a migration:
enable_extension "heroku_ext.pgcrypto" enable_extension "pg_stat_statements"then the generated schema dump will also contain:
enable_extension "heroku_ext.pgcrypto" enable_extension "pg_stat_statements"Tony Novak
-
Fix
ActiveRecord::Encryption::EncryptedAttributeType#typeto return actual cast type.Vasiliy Ermolovich
-
SQLite3Adapter: Bulk insert fixtures.
Previously one insert command was executed for each fixture, now they are aggregated in a single bulk insert command.
Lázaro Nixon
-
PostgreSQLAdapter: Allow
disable_extensionto be called with schema-qualified name.For parity with
enable_extension, thedisable_extensionmethod can be called with a schema-qualified name (e.g.disable_extension "myschema.pgcrypto"). Note that PostgreSQL'sDROP EXTENSIONdoes not actually take a schema name (unlikeCREATE EXTENSION), so the resulting SQL statement will only name the extension, e.g.DROP EXTENSION IF EXISTS "pgcrypto".Tony Novak
-
Make
create_schema/drop_schemareversible in migrations.Previously,
create_schemaanddrop_schemawere irreversible migration operations.Tony Novak
-
Support batching using custom columns.
Product.in_batches(cursor: [:shop_id, :id]) do |relation| # do something with relation endfatkodima
-
Use SQLite
IMMEDIATEtransactions when possible.Transactions run against the SQLite3 adapter default to IMMEDIATE mode to improve concurrency support and avoid busy exceptions.
Stephen Margheim
-
Raise specific exception when a connection is not defined.
The new
ConnectionNotDefinedexception provides connection name, shard and role accessors indicating the details of the connection that was requested.Hana Harencarova, Matthew Draper
-
Delete the deprecated constant
ActiveRecord::ImmutableRelation.Xavier Noria
-
Fix duplicate callback execution when child autosaves parent with
has_oneandbelongs_to.Before, persisting a new child record with a new associated parent record would run
before_validation,after_validation,before_saveandafter_savecallbacks twice.Now, these callbacks are only executed once as expected.
Joshua Young
-
ActiveRecord::Encryption::Encryptornow supports a:compressoroption to customize the compression algorithm used.module ZstdCompressor def self.deflate(data) Zstd.compress(data) end def self.inflate(data) Zstd.decompress(data) end end class User encrypts :name, compressor: ZstdCompressor endYou disable compression by passing
compress: false.class User encrypts :name, compress: false endheka1024
-
Add condensed
#inspectforConnectionPool,AbstractAdapter, andDatabaseConfig.Hartley McGuire
-
Add
.shard_keys,.sharded?, &.connected_to_all_shardsmethods.class ShardedBase < ActiveRecord::Base self.abstract_class = true connects_to shards: { shard_one: { writing: :shard_one }, shard_two: { writing: :shard_two } } end class ShardedModel < ShardedBase end ShardedModel.shard_keys => [:shard_one, :shard_two] ShardedModel.sharded? => true ShardedBase.connected_to_all_shards { ShardedModel.current_shard } => [:shard_one, :shard_two]Nony Dutton
-
Add a
filteroption toin_order_ofto prioritize certain values in the sorting without filtering the results by these values.Igor Depolli
-
Fix an issue where the IDs reader method did not return expected results for preloaded associations in models using composite primary keys.
Jay Ang
-
Allow to configure
strict_loading_modeglobally or within a model.Defaults to
:all, can be changed to:n_plus_one_only.Garen Torikian
-
Add
ActiveRecord::Relation#readonly?.Reflects if the relation has been marked as readonly.
Theodor Tonum
-
Improve
ActiveRecord::Storeto raise a descriptive exception if the column is not either structured (e.g., PostgreSQL +hstore+/+json+, or MySQL +json+) or declared serializable viaActiveRecord.store.Previously, a
NoMethodErrorwould be raised when the accessor was read or written:NoMethodError: undefined method `accessor' for an instance of ActiveRecord::Type::TextNow, a descriptive
ConfigurationErroris raised:ActiveRecord::ConfigurationError: the column 'metadata' has not been configured as a store. Please make sure the column is declared serializable via 'ActiveRecord.store' or, if your database supports it, use a structured column type like hstore or json.Mike Dalessio
-
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
-
Add public method for checking if a table is ignored by the schema cache.
Previously, an application would need to reimplement
ignored_table?from the schema cache class to check if a table was set to be ignored. This adds a public method to support this and updates the schema cache to use that directly.ActiveRecord.schema_cache_ignored_tables = ["developers"] ActiveRecord.schema_cache_ignored_table?("developers") => trueEileen M. Uchitelle
Action View
-
Remove deprecated support to passing a content to void tag elements on the
tagbuilder.Rafael Mendonça França
-
Remove deprecated support to passing
nilto themodel:argument ofform_with.Rafael Mendonça França
-
Enable DependencyTracker to evaluate renders with trailing interpolation.
<%= render "maintenance_tasks/runs/info/#{run.status}" %>Previously, the DependencyTracker would ignore this render, but now it will mark all partials in the "maintenance_tasks/runs/info" folder as dependencies.
Hartley McGuire
-
Rename
text_areamethods intotextareaOld names are still available as aliases.
Sean Doyle
-
Rename
check_box*methods intocheckbox*.Old names are still available as aliases.
Jean Boussier
Action Pack
-
Fix routes with
::in the path.Rafael Mendonça França
-
Maintain Rack 2 parameter parsing behaviour.
Matthew Draper
-
Remove
Rails.application.config.action_controller.allow_deprecated_parameters_hash_equality.Rafael Mendonça França
-
Improve
ActionController::TestCaseto expose a binary encodedrequest.body.The rack spec clearly states:
The input stream is an IO-like object which contains the raw HTTP POST data. When applicable, its external encoding must be “ASCII-8BIT” and it must be opened in binary mode.
Until now its encoding was generally UTF-8, which doesn't accurately reflect production behavior.
Jean Boussier
-
Update
ActionController::AllowBrowserto support passing method names to:blockclass ApplicationController < ActionController::Base allow_browser versions: :modern, block: :handle_outdated_browser private def handle_outdated_browser render file: Rails.root.join("public/custom-error.html"), status: :not_acceptable end endSean Doyle
-
Raise an
ArgumentErrorwhen invalid:onlyor:exceptoptions are passed into#resourceand#resources.Joshua Young
-
Fix non-GET requests not updating cookies in
ActionController::TestCase.Jon Moss, Hartley McGuire
-
Update
ActionController::Liveto use a thread-pool to reuse threads across requests.Adam Renberg Tamm
-
Introduce safer, more explicit params handling method with
params#expectsuch thatparams.expect(table: [ :attr ])replacesparams.require(:table).permit(:attr)Ensures params are filtered with consideration for the expected types of values, improving handling of params and avoiding ignorable errors caused by params tampering.
# If the url is altered to ?person=hacked # Before params.require(:person).permit(:name, :age, pets: [:name]) # raises NoMethodError, causing a 500 and potential error reporting # After params.expect(person: [ :name, :age, pets: [[:name]] ]) # raises ActionController::ParameterMissing, correctly returning a 400 errorYou may also notice the new double array
[[:name]]. In order to declare when a param is expected to be an array of parameter hashes, this new double array syntax is used to explicitly declare an array.expectrequires you to declare expected arrays in this way, and will ignore arrays that are passed when, for example,pet: [:name]is used.In order to preserve compatibility,
permitdoes not adopt the new double array syntax and is therefore more permissive about unexpected types. Usingexpecteverywhere is recommended.We suggest replacing
params.require(:person).permit(:name, :age)with the direct replacementparams.expect(person: [:name, :age])to prevent external users from manipulating params to trigger 500 errors. A 400 error will be returned instead, using public/400.htmlUsage of
params.require(:id)should likewise be replaced withparams.expect(:id)which is designed to ensure thatparams[:id]is a scalar and not an array or hash, also requiring the param.# Before User.find(params.require(:id)) # allows an array, altering behavior # After User.find(params.expect(:id)) # expect only returns non-blank permitted scalars (excludes Hash, Array, nil, "", etc)Martin Emde
-
System Testing: Disable Chrome's search engine choice by default in system tests.
glaszig
-
Fix
Request#raw_postraisingNoMethodErrorwhenrack.inputisnil.Hartley McGuire
-
Remove
raccdependency by manually writingActionDispatch::Journey::Scanner.Gannon McGibbon
-
Speed up
ActionDispatch::Routing::Mapper::Scope#[]by merging frame hashes.Gannon McGibbon
-
Allow bots to ignore
allow_browser.Matthew Nguyen
-
Deprecate drawing routes with multiple paths to make routing faster. You may use
with_optionsor a loop to make drawing multiple paths easier.# Before get "/users", "/other_path", to: "users#index" # After get "/users", to: "users#index" get "/other_path", to: "users#index"Gannon McGibbon
-
Make
http_cache_foreveruseimmutable: trueNate Matykiewicz
-
Add
config.action_dispatch.strict_freshness.When set to
true, theETagheader takes precedence over theLast-Modifiedheader when both are present, as specified by RFC 7232, Section 6.Defaults to
falseto maintain compatibility with previous versions of Rails, but is enabled as part of Rails 8.0 defaults.heka1024
-
Support
immutabledirective in Cache-Controlexpires_in 1.minute, public: true, immutable: true # Cache-Control: public, max-age=60, immutableheka1024
-
Add
:wasm_unsafe_evalmapping forcontent_security_policy# Before policy.script_src "'wasm-unsafe-eval'" # After policy.script_src :wasm_unsafe_evalJoe Haig
-
Add
display_captureandkeyboard_mapinpermissions_policyCyril Blaecke
-
Add
connectroute helper.Samuel Williams
Active Job
-
Remove deprecated
config.active_job.use_big_decimal_serializer.Rafael Mendonça França
-
Deprecate
sucker_punchas an adapter option.If you're using this adapter, change to
adapter: asyncfor the same functionality.Dino Maric, zzak
-
Use
RAILS_MAX_THREADSinActiveJob::AsyncAdapter. If it is not set, use 5 as default.heka1024
Action Mailer
- No changes.
Action Cable
-
Add an
identifierto the event payload for the ActiveSupport::Notificationtransmit_subscription_confirmation.action_cableandtransmit_subscription_rejection.action_cable.Keith Schacht
Active Storage
-
Deprecate
ActiveStorage::Service::AzureStorageService.zzak
-
Improve
ActiveStorage::Filename#sanitizedmethod to handle special characters more effectively. Replace the characters"*?<>with-if they exist in the Filename to match the Filename convention of Win OS.Luong Viet Dung(Martin)
-
Improve InvariableError, UnpreviewableError and UnrepresentableError message.
Include Blob ID and content_type in the messages.
Petrik de Heus
-
Mark proxied files as
immutablein their Cache-Control headerNate Matykiewicz
Action Mailbox
- No changes.
Action Text
-
Dispatch direct-upload events on attachment uploads
When using Action Text's rich textarea, it's possible to attach files to the editor. Previously, that action didn't dispatch any events, which made it hard to react to the file uploads. For instance, if an upload failed, there was no way to notify the user about it, or remove the attachment from the editor.
This commits adds new events -
direct-upload:start,direct-upload:progress, anddirect-upload:end- similar to how Active Storage's direct uploads work.Matheus Richard, Brad Rees
-
Add
store_if_blankoption tohas_rich_textPass
store_if_blank: falseto not createActionText::RichTextrecords when saving with a blank attribute, such as from an optional form parameter.class Message has_rich_text :content, store_if_blank: false end Message.create(content: "hi") # creates an ActionText::RichText Message.create(content: "") # does not create an ActionText::RichTextAlex Ghiculescu
-
Strip
contentattribute if the key is present but the value is emptyJeremy Green
-
Rename
rich_text_areamethods intorich_textareaOld names are still available as aliases.
Sean Doyle
-
Only sanitize
contentattribute when present in attachments.Petrik de Heus
Railties
-
Fix incorrect database.yml with
skip_solid.Joé Dupuis
-
Set
Regexp.timeoutto1s by default to improve security over Regexp Denial-of-Service attacks.Rafael Mendonça França
-
Remove deprecated support to extend Rails console through
Rails::ConsoleMethods.Rafael Mendonça França
-
Remove deprecated file
rails/console/helpers.Rafael Mendonça França
-
Remove deprecated file
rails/console/app.Rafael Mendonça França
-
Remove deprecated
config.read_encrypted_secrets.Rafael Mendonça França
-
Add Kamal support for devcontainers
Previously generated devcontainer could not use docker and therefore Kamal.
Joé Dupuis
-
Exit
rails gwith code 1 if generator could not be found.Previously
rails greturned 0, which would make it harder to catch typos in scripts callingrails g.Christopher Özbek
-
Remove
require_*statements from application.css to align with the transition from Sprockets to Propshaft.With Propshaft as the default asset pipeline in Rails 8, the require_tree and require_self clauses in application.css are no longer necessary, as they were specific to Sprockets. Additionally, the comment has been updated to clarify that CSS precedence now follows standard cascading order without automatic prioritization by the asset pipeline.
Eduardo Alencar
-
Do not include redis by default in generated Dev Containers.
Now that applications use the Solid Queue and Solid Cache gems by default, we do not need to include redis in the Dev Container. We will only include redis if
--skip-solidis used when generating an app that uses Active Job or Action Cable.When generating a Dev Container for an existing app, we will not include redis if either of the solid gems are in use.
Andrew Novoselac
-
Use Solid Cable as the default Action Cable adapter in production, configured as a separate queue database in config/database.yml. It keeps messages in a table and continuously polls for updates. This makes it possible to drop the common dependency on Redis, if it isn't needed for any other purpose. Despite polling, the performance of Solid Cable is comparable to Redis in most situations. And in all circumstances, it makes it easier to deploy Rails when Redis is no longer a required dependency for Action Cable functionality.
DHH
-
Use Solid Queue as the default Active Job backend in production, configured as a separate queue database in config/database.yml. In a single-server deployment, it'll run as a Puma plugin. This is configured in
config/deploy.ymland can easily be changed to use a dedicated jobs machine.DHH
-
Use Solid Cache as the default Rails.cache backend in production, configured as a separate cache database in config/database.yml.
DHH
-
Add Rails::Rack::SilenceRequest middleware and use it via
config.silence_healthcheck_path = pathto silence requests to "/up". This prevents the Kamal-required health checks from clogging up the production logs.DHH
-
Introduce
mariadb-mysqlandmariadb-trilogydatabase options forrails newWhen used with the
--devcontainerflag, these options will usemariadbas the database for the Dev Container. The originalmysqlandtrilogyoptions will usemysql. Users who are not generating a Dev Container do not need to use the new options.Andrew Novoselac
-
Deprecate
::STATS_DIRECTORIES.The global constant
STATS_DIRECTORIEShas been deprecated in favor ofRails::CodeStatistics.register_directory.Add extra directories with
Rails::CodeStatistics.register_directory(label, path):require "rails/code_statistics" Rails::CodeStatistics.register_directory('My Directory', 'path/to/dir')Petrik de Heus
-
Enable query log tags by default on development env
This can be used to trace troublesome SQL statements back to the application code that generated these statements. It is also useful when using multiple databases because the query logs can identify which database is being used.
Matheus Richard
-
Defer route drawing to the first request, or when url_helpers are called
Executes the first routes reload in middleware, or when a route set's url_helpers receives a route call / asked if it responds to a route. Previously, this was executed unconditionally on boot, which can slow down boot time unnecessarily for larger apps with lots of routes.
Environments like production that have
config.eager_load = truewill continue to eagerly load routes on boot.Gannon McGibbon
-
Generate form helpers to use
textarea*methods instead oftext_area*methodsSean Doyle
-
Add authentication generator to give a basic start to an authentication system using database-tracked sessions and password reset.
Generate with...
bin/rails generate authenticationGenerated files:
app/models/current.rb app/models/user.rb app/models/session.rb app/controllers/sessions_controller.rb app/controllers/passwords_controller.rb app/mailers/passwords_mailer.rb app/views/sessions/new.html.erb app/views/passwords/new.html.erb app/views/passwords/edit.html.erb app/views/passwords_mailer/reset.html.erb app/views/passwords_mailer/reset.text.erb db/migrate/xxxxxxx_create_users.rb db/migrate/xxxxxxx_create_sessions.rb test/mailers/previews/passwords_mailer_preview.rbDHH
-
Add not-null type modifier to migration attributes.
Generating with...
bin/rails generate migration CreateUsers email_address:string!:uniq password_digest:string!Produces:
class CreateUsers < ActiveRecord::Migration[8.0] def change create_table :users do |t| t.string :email_address, null: false t.string :password_digest, null: false t.timestamps end add_index :users, :email_address, unique: true end endDHH
-
Add a
scriptfolder to applications, and a scripts generator.The new
scriptfolder is meant to hold one-off or general purpose scripts, such as data migration scripts, cleanup scripts, etc.A new script generator allows you to create such scripts:
bin/rails generate script my_script bin/rails generate script data/backfillYou can run the generated script using:
bundle exec ruby script/my_script.rb bundle exec ruby script/data/backfill.rbJerome Dalbert, Haroon Ahmed
-
Deprecate
bin/rake statsin favor ofbin/rails stats.Juan Vásquez
-
Add internal page
/rails/info/notes, that displays the same information asbin/rails notes.Deepak Mahakale
-
Add Rubocop and GitHub Actions to plugin generator. This can be skipped using --skip-rubocop and --skip-ci.
Chris Oliver
-
Use Kamal for deployment by default, which includes generating a Rails-specific config/deploy.yml. This can be skipped using --skip-kamal. See more: https://kamal-deploy.org/
DHH
Guides
-
The guide Classic to Zeitwerk HOWTO that documented how to migrate from the
classicautoloader to Zeitwerk has been deleted.The last version of this guide can be found here, in case you need it.
Petrik de Heus
Active Support
-
Fix
Enumerable#soleto return the full tuple instead of just the first element of the tuple.Olivier Bellone
-
Fix parallel tests hanging when worker processes die abruptly.
Previously, if a worker process was killed (e.g., OOM killed,
kill -9) during parallel test execution, the test suite would hang forever waiting for the dead worker.Joshua Young
-
ActiveSupport::FileUpdateCheckerdoes not depend onTime.nowto prevent unnecessary reloads with time travel test helpersJan Grodowski
-
Fix
ActiveSupport::BroadcastLoggerfrom executing a block argument for each logger (tagged, info, etc.).Jared Armstrong
-
Fix
ActiveSupport::HashWithIndifferentAccess#transform_keys!removing defaults.Hartley McGuire
-
Fix
ActiveSupport::HashWithIndifferentAccess#tranform_keys!to handle collisions.If the transformation would result in a key equal to another not yet transformed one, it would result in keys being lost.
Before:
>> {a: 1, b: 2}.with_indifferent_access.transform_keys!(&:succ) => {"c" => 1}After:
>> {a: 1, b: 2}.with_indifferent_access.transform_keys!(&:succ) => {"c" => 1, "d" => 2}Jason T Johnson, Jean Boussier
-
Fix
ActiveSupport::Cache::MemCacheStore#read_multito handle network errors.This method specifically wasn't handling network errors like other codepaths.
Alessandro Dal Grande
-
Fix Active Support Cache
fetch_multiwhen local store is active.fetch_multinow properly yield to the provided block for missing entries that have been recorded as such in the local store.Jean Boussier
-
Fix execution wrapping to report all exceptions, including
Exception.If a more serious error like
SystemStackErrororNoMemoryErrorhappens, the error reporter should be able to report these kinds of exceptions.Gannon McGibbon
-
Fix
RedisCacheStoreandMemCacheStoreto also handle connection pool related errors.These errors are rescued and reported to
Rails.error.Jean Boussier
-
Fix
ActiveSupport::Cache#read_multito respect version expiry when using local cache.zzak
-
Fix
ActiveSupport::MessageVerifierandActiveSupport::MessageEncryptorconfiguration ofon_rotationcallback.verifier.rotate(old_secret).on_rotation { ... }Now both work as documented.
Jean Boussier
-
Fix
ActiveSupport::MessageVerifierto always be able to verify both URL-safe and URL-unsafe payloads.This is to allow transitioning seemlessly from either configuration without immediately invalidating all previously generated signed messages.
Jean Boussier, Florent Beaurain, Ali Sepehri
-
Fix
cache.fetchto honor the provided expiry when:race_condition_ttlis used.cache.fetch("key", expires_in: 1.hour, race_condition_ttl: 5.second) do "something" endIn the above example, the final cache entry would have a 10 seconds TTL instead of the requested 1 hour.
Dhia
-
Better handle procs with splat arguments in
set_callback.Radamés Roriz
-
Fix
String#mb_charsto not mutate the receiver.Previously it would call
force_encodingon the receiver, now it dups the receiver first.Jean Boussier
-
Improve
ErrorSubscriberto also mark error causes as reported.This avoid some cases of errors being reported twice, notably in views because of how errors are wrapped in
ActionView::Template::Error.Jean Boussier
-
Fix
Module#module_parent_nameto return the correct name after the module has been named.When called on an anonymous module, the return value wouldn't change after the module was given a name later by being assigned to a constant.
mod = Module.new mod.module_parent_name # => "Object" MyModule::Something = mod mod.module_parent_name # => "MyModule"Jean Boussier
-
Fix a bug in
ERB::Util.tokenizethat causes incorrect tokenization when ERB tags are preceeded by multibyte characters.Martin Emde
Active Model
-
Fix
has_secure_passwordto perform confirmation validation of the password even when blank.The validation was incorrectly skipped when the password only contained whitespace characters.
Fabio Sangiovanni
-
Handle missing attributes for
ActiveModel::Translation#human_attribute_name.zzak
-
Fix
ActiveModel::AttributeAssignment#assign_attributesto accept objects withouteach.Kouhei Yanagita
Active Record
-
Fix SQLite3 data loss during table alterations with CASCADE foreign keys.
When altering a table in SQLite3 that is referenced by child tables with
ON DELETE CASCADEforeign keys, ActiveRecord would silently delete all data from the child tables. This occurred because SQLite requires table recreation for schema changes, and during this process the original table is temporarily dropped, triggering CASCADE deletes on child tables.The root cause was incorrect ordering of operations. The original code wrapped
disable_referential_integrityinside a transaction, butPRAGMA foreign_keyscannot be modified inside a transaction in SQLite - attempting to do so simply has no effect. This meant foreign keys remained enabled during table recreation, causing CASCADE deletes to fire.The fix reverses the order to follow the official SQLite 12-step ALTER TABLE procedure:
disable_referential_integritynow wraps the transaction instead of being wrapped by it. This ensures foreign keys are properly disabled before the transaction starts and re-enabled after it commits, preventing CASCADE deletes while maintaining data integrity through atomic transactions.Ruy Rocha
-
Fix
belongs_toassociations not to clear the entire composite primary key.When clearing a
belongs_toassociation that references a model with composite primary key, only the optional part of the key should be cleared.zzak
-
Fix invalid records being autosaved when distantly associated records are marked for deletion.
Ian Terrell, axlekb AB
-
Prevent persisting invalid record.
Edouard Chin
-
Fix count with group by qualified name on loaded relation.
Ryuta Kamizono
-
Fix
sumwith qualified name on loaded relation.Chris Gunther
-
Fix prepared statements on mysql2 adapter.
Jean Boussier
-
Fix query cache for pinned connections in multi threaded transactional tests.
When a pinned connection is used across separate threads, they now use a separate cache store for each thread.
This improve accuracy of system tests, and any test using multiple threads.
Heinrich Lee Yu, Jean Boussier
-
Don't add
id_valueattribute alias when attribute/column with that name already exists.Rob Lewis
-
Fix false positive change detection involving STI and polymorhic has one relationships.
Polymorphic
has_onerelationships would always be considered changed when defined in a STI child class, causing nedless extra autosaves.David Fritsch
-
Fix stale associaton detection for polymophic
belong_to.Florent Beaurain, Thomas Crambert
-
Fix removal of PostgreSQL version comments in
structure.sqlfor latest PostgreSQL versions which include\restrict.Brendan Weibrecht
-
Fix
#mergewith#oror#andand a mixture of attributes and SQL strings resulting in an incorrect query.base = Comment.joins(:post).where(user_id: 1).where("recent = 1") puts base.merge(base.where(draft: true).or(Post.where(archived: true))).to_sqlBefore:
SELECT "comments".* FROM "comments"
INNER JOIN "posts" ON "posts"."id" = "comments"."post_id"
WHERE (recent = 1)
AND (
"comments"."user_id" = 1
AND (recent = 1)
AND "comments"."draft" = 1
OR "posts"."archived" = 1
)
```
After:
```sql
SELECT "comments".* FROM "comments"
INNER JOIN "posts" ON "posts"."id" = "comments"."post_id"
WHERE "comments"."user_id" = 1
AND (recent = 1)
AND (
"comments"."user_id" = 1
AND (recent = 1)
AND "comments"."draft" = 1
OR "posts"."archived" = 1
)
```
*Joshua Young*
* Fix inline `has_and_belongs_to_many` fixtures for tables with composite primary keys.
*fatkodima*
* Fix `annotate` comments to propagate to `update_all`/`delete_all`.
*fatkodima*
* Fix checking whether an unpersisted record is `include?`d in a strictly
loaded `has_and_belongs_to_many` association.
*Hartley McGuire*
* Fix inline has_and_belongs_to_many fixtures for tables with composite primary keys.
*fatkodima*
* `create_or_find_by` will now correctly rollback a transaction.
When using `create_or_find_by`, raising a ActiveRecord::Rollback error
in a `after_save` callback had no effect, the transaction was committed
and a record created.
*Edouard Chin*
* Gracefully handle `Timeout.timeout` firing during connection configuration.
Use of `Timeout.timeout` could result in improperly initialized database connection.
This could lead to a partially configured connection being used, resulting in various exceptions,
the most common being with the PostgreSQLAdapter raising `undefined method 'key?' for nil`
or `TypeError: wrong argument type nil (expected PG::TypeMap)`.
*Jean Boussier*
* The SQLite3 adapter quotes non-finite Numeric values like "Infinity" and "NaN".
*Mike Dalessio*
* Handle libpq returning a database version of 0 on no/bad connection in `PostgreSQLAdapter`.
Before, this version would be cached and an error would be raised during connection configuration when
comparing it with the minimum required version for the adapter. This meant that the connection could
never be successfully configured on subsequent reconnection attempts.
Now, this is treated as a connection failure consistent with libpq, raising a `ActiveRecord::ConnectionFailed`
and ensuring the version isn't cached, which allows the version to be retrieved on the next connection attempt.
*Joshua Young*, *Rian McGuire*
* Fix error handling during connection configuration.
Active Record wasn't properly handling errors during the connection configuration phase.
This could lead to a partially configured connection being used, resulting in various exceptions,
the most common being with the PostgreSQLAdapter raising `undefined method `key?' for nil`
or `TypeError: wrong argument type nil (expected PG::TypeMap)`.
*Jean Boussier*
* Fix a case where a non-retryable query could be marked retryable.
*Hartley McGuire*
* Handle circular references when autosaving associations.
*zzak*
* Prevent persisting invalid record.
*Edouard Chin*
* Fix support for PostgreSQL enum types with commas in their name.
*Arthur Hess*
* Fix inserts on MySQL with no RETURNING support for a table with multiple auto populated columns.
*Nikita Vasilevsky*
* Fix joining on a scoped association with string joins and bind parameters.
```ruby
class Instructor < ActiveRecord::Base
has_many :instructor_roles, -> { active }
end
class InstructorRole < ActiveRecord::Base
scope :active, -> {
joins("JOIN students ON instructor_roles.student_id = students.id")
.where(students { status: 1 })
}
end
Instructor.joins(:instructor_roles).first
```
The above example would result in `ActiveRecord::StatementInvalid` because the
`active` scope bind parameters would be lost.
*Jean Boussier*
* Fix a potential race condition with system tests and transactional fixtures.
*Sjoerd Lagarde*
* Fix count with group by qualified name on loaded relation.
*Ryuta Kamizono*
* Fix sum with qualified name on loaded relation.
*Chris Gunther*
* Fix autosave associations to no longer validated unmodified associated records.
Active Record was incorrectly performing validation on associated record that
weren't created nor modified as part of the transaction:
```ruby
Post.create!(author: User.find(1)) # Fail if user is invalid
```
*Jean Boussier*
* Remember when a database connection has recently been verified (for
two seconds, by default), to avoid repeated reverifications during a
single request.
This should recreate a similar rate of verification as in Rails 7.1,
where connections are leased for the duration of a request, and thus
only verified once.
*Matthew Draper*
* Fix prepared statements on mysql2 adapter.
*Jean Boussier*
* Fix a race condition in `ActiveRecord::Base#method_missing` when lazily defining attributes.
If multiple thread were concurrently triggering attribute definition on the same model,
it could result in a `NoMethodError` being raised.
*Jean Boussier*
* Fix MySQL default functions getting dropped when changing a column's nullability.
*Bastian Bartmann*
* Fix `add_unique_constraint`/`add_check_constraint`/`/`add_foreign_key` to be revertible when
given invalid options.
*fatkodima*
* Fix asynchronous destroying of polymorphic `belongs_to` associations.
*fatkodima*
* NOT VALID constraints should not dump in `create_table`.
*Ryuta Kamizono*
* Fix finding by nil composite primary key association.
*fatkodima*
* Fix parsing of SQLite foreign key names when they contain non-ASCII characters
*Zacharias Knudsen*
* Fix parsing of MySQL 8.0.16+ CHECK constraints when they contain new lines.
*Steve Hill*
* Ensure normalized attribute queries use `IS NULL` consistently for `nil` and normalized `nil` values.
*Joshua Young*
* Restore back the ability to pass only database name for `DATABASE_URL`.
*fatkodima*
* Fix `order` with using association name as an alias.
*Ryuta Kamizono*
* Improve invalid argument error for with.
*Ryuta Kamizono*
* Deduplicate `with` CTE expressions.
*fatkodima*
## Action View
* Fix `javascript_include_tag` `type` option to accept either strings and symbols.
```ruby
javascript_include_tag "application", type: :module
javascript_include_tag "application", type: "module"
```
Previously, only the string value was recoginized.
*Jean Boussier*
* Fix `excerpt` helper with non-whitespace separator.
*Jonathan Hefner*
* Respect `html_options[:form]` when `collection_checkboxes` generates the
hidden `<input>`.
*Riccardo Odone*
* Layouts have access to local variables passed to `render`.
This fixes #31680 which was a regression in Rails 5.1.
*Mike Dalessio*
* Argument errors related to strict locals in templates now raise an
`ActionView::StrictLocalsError`, and all other argument errors are reraised as-is.
Previously, any `ArgumentError` raised during template rendering was swallowed during strict
local error handling, so that an `ArgumentError` unrelated to strict locals (e.g., a helper
method invoked with incorrect arguments) would be replaced by a similar `ArgumentError` with an
unrelated backtrace, making it difficult to debug templates.
Now, any `ArgumentError` unrelated to strict locals is reraised, preserving the original
backtrace for developers.
Also note that `ActionView::StrictLocalsError` is a subclass of `ArgumentError`, so any existing
code that rescues `ArgumentError` will continue to work.
Fixes #52227.
*Mike Dalessio*
* Fix stack overflow error in dependency tracker when dealing with circular dependencies
*Jean Boussier*
* Fix a crash in ERB template error highlighting when the error occurs on a
line in the compiled template that is past the end of the source template.
*Martin Emde*
* Improve reliability of ERB template error highlighting.
Fix infinite loops and crashes in highlighting and
improve tolerance for alternate ERB handlers.
*Martin Emde*
## Action Pack
* Submit test requests using `as: :html` with `Content-Type: x-www-form-urlencoded`
*Sean Doyle*
* Address `rack 3.2` deprecations warnings.
```
warning: Status code :unprocessable_entity is deprecated and will be removed in a future version of Rack.
Please use :unprocessable_content instead.
```
Rails API will transparently convert one into the other for the forseable future.
*Earlopain*, *Jean Boussier*
* Always return empty body for HEAD requests in `PublicExceptions` and
`DebugExceptions`.
This is required by `Rack::Lint` (per RFC9110).
*Hartley McGuire*
* Fix `url_for` to handle `:path_params` gracefully when it's not a `Hash`.
Prevents various security scanners from causing exceptions.
*Martin Emde*
* Fix `ActionDispatch::Executor` to unwrap exceptions like other error reporting middlewares.
*Jean Boussier*
* Fix NoMethodError when a non-string CSRF token is passed through headers.
*Ryan Heneise*
* Fix invalid response when rescuing `ActionController::Redirecting::UnsafeRedirectError` in a controller.
*Alex Ghiculescu*
## Active Job
* Include the actual Active Job locale when serializing rather than I18n locale.
*Adrien S*
* Avoid crashing in Active Job logger when logging enqueueing errors
`ActiveJob.perform_all_later` could fail with a `TypeError` when all
provided jobs failed to be enqueueed.
*Efstathios Stivaros*
## Action Mailer
* No changes.
## Action Cable
* Fixed compatibility with `redis` gem `5.4.1`
*Jean Boussier*
* Fixed a possible race condition in `stream_from`.
*OuYangJinTing*
* Ensure the Postgresql adapter always use a dedicated connection even during system tests.
Fix an issue with the Action Cable Postgresql adapter causing deadlock or various weird
pg client error during system tests.
*Jean Boussier*
## Active Storage
* Fix `config.active_storage.touch_attachment_records` to work with eager loading.
*fatkodima*
* A Blob will no longer autosave associated Attachment.
This fixes an issue where a record with an attachment would have
its dirty attributes reset, preventing your `after commit` callbacks
on that record to behave as expected.
Note that this change doesn't require any changes on your application
and is supposed to be internal. Active Storage Attachment will continue
to be autosaved (through a different relation).
*Edouard-chin*
## Action Mailbox
* No changes.
## Action Text
* No changes.
## Railties
* Use `secret_key_base` from ENV or credentials when present locally.
When ENV["SECRET_KEY_BASE"] or
`Rails.application.credentials.secret_key_base` is set for test or
development, it is used for the `Rails.config.secret_key_base`,
instead of generating a `tmp/local_secret.txt` file.
*Petrik de Heus*
## Guides
* No changes.
Active Support
-
Include options when instrumenting
ActiveSupport::Cache::Store#deleteandActiveSupport::Cache::Store#delete_multi.Adam Renberg Tamm
-
Print test names when running
rails test -vfor parallel tests.John Hawthorn, Abeid Ahmed
Active Model
-
Fix regression in
alias_attributeto work with user defined methods.alias_attributewould wrongly assume the attribute accessor was generated by Active Model.class Person include ActiveModel::AttributeMethods define_attribute_methods :name attr_accessor :name alias_attribute :full_name, :name end person.full_name # => NoMethodError: undefined method `attribute' for an instance of PersonJean Boussier
Active Record
-
Fix support for
query_cache: falseindatabase.yml.query_cache: falsewould no longer entirely disable the Active Record query cache.zzak
-
Set
.attributes_for_inspectto:allby default.For new applications it is set to
[:id]in config/environment/production.rb.In the console all the attributes are always shown.
Andrew Novoselac
-
PG::UnableToSend: no connection to the serveris now retryable as a connection-related exceptionKazuma Watanabe
-
Fix marshalling of unsaved associated records in 7.1 format.
The 7.1 format would only marshal associated records if the association was loaded. But associations that would only contain unsaved records would be skipped.
Jean Boussier
-
Fix incorrect SQL query when passing an empty hash to
ActiveRecord::Base.insert.David Stosik
-
Allow to save records with polymorphic join tables that have
inverse_ofspecified.Markus Doits
-
Fix association scopes applying on the incorrect join when using a polymorphic
has_many through:.Joshua Young
-
Fix
dependent: :destroyfor bi-directional has one through association.Fixes #50948.
class Left < ActiveRecord::Base has_one :middle, dependent: :destroy has_one :right, through: :middle end class Middle < ActiveRecord::Base belongs_to :left, dependent: :destroy belongs_to :right, dependent: :destroy end class Right < ActiveRecord::Base has_one :middle, dependent: :destroy has_one :left, through: :middle endIn the above example
left.destroywouldn't destroy its associatedRightrecord.Andy Stewart
-
Properly handle lazily pinned connection pools.
Fixes #53147.
When using transactional fixtures with system tests to similar tools such as capybara, it could happen that a connection end up pinned by the server thread rather than the test thread, causing
"Cannot expire connection, it is owned by a different thread"errors.Jean Boussier
-
Fix
ActiveRecord::Base.withto accept more than two sub queries.Fixes #53110.
User.with(foo: [User.select(:id), User.select(:id), User.select(:id)]).to_sql undefined method `union' for an instance of Arel::Nodes::UnionAll (NoMethodError)The above now works as expected.
fatkodima
-
Properly release pinned connections with non joinable connections.
Fixes #52973
When running system tests with transactional fixtures on, it could happen that the connection leased by the Puma thread wouldn't be properly released back to the pool, causing "Cannot expire connection, it is owned by a different thread" errors in later tests.
Jean Boussier
-
Make Float distinguish between
float4andfloat8in PostgreSQL.Fixes #52742
Ryota Kitazawa, Takayuki Nagatomi
-
Fix an issue where
.left_outer_joinsused with multiple associations that have the same child association but different parents does not join all parents.Previously, using
.left_outer_joinswith the same child association would only join one of the parents.Now it will correctly join both parents.
Fixes #41498.
Garrett Blehm
-
Ensure
ActiveRecord::Encryption.configis always ready before access.Previously,
ActiveRecord::Encryptionconfiguration was deferred untilActiveRecord::Basewas loaded. Therefore, accessingActiveRecord::Encryption.configproperties beforeActiveRecord::Basewas loaded would give incorrect results.ActiveRecord::Encryptionnow has its own loading hook so that its configuration is set as soon as needed.When
ActiveRecord::Baseis loaded, even lazily, it in turn triggers the loading ofActiveRecord::Encryption, thus preserving the original behavior of having its config ready before any use ofActiveRecord::Base.Maxime Réty
-
Add
TimeZoneConverter#==method, so objects will be properly compared by their type, scale, limit & precision.Address #52699.
Ruy Rocha
Action View
- No changes.
Action Pack
-
Fix non-GET requests not updating cookies in
ActionController::TestCase.Jon Moss, Hartley McGuire
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Guides
- No changes.
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Fix detection for
enumcolumns with parallelized tests and PostgreSQL.Rafael Mendonça França
-
Allow to eager load nested nil associations.
fatkodima
-
Fix swallowing ignore order warning when batching using
BatchEnumerator.fatkodima
-
Fix memory bloat on the connection pool when using the Fiber
IsolatedExecutionState.Jean Boussier
-
Restore inferred association class with the same modularized name.
Justin Ko
-
Fix
ActiveRecord::Base.inspectto properly explain how to load schema information.Jean Boussier
-
Check invalid
enumoptions for the new syntax.The options using
_prefix in the old syntax are invalid in the new syntax.Rafael Mendonça França
-
Fix
ActiveRecord::Encryption::EncryptedAttributeType#typeto return actual cast type.Vasiliy Ermolovich
-
Fix
create_tablewith:auto_incrementoption for MySQL adapter.fatkodima
Action View
- No changes.
Action Pack
-
Fix
Request#raw_postraisingNoMethodErrorwhenrack.inputisnil.Hartley McGuire
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
-
Strip
contentattribute if the key is present but the value is emptyJeremy Green
Railties
-
Fix
rails consolefor application with non default application constant.The wrongly assumed the Rails application would be named
AppNamespace::Application, which is the default but not an obligation.Jean Boussier
-
Fix the default Dockerfile to include the full sqlite3 package.
Prior to this it only included
libsqlite3, so it wasn't enough to runrails dbconsole.Jerome Dalbert
-
Don't update public directory during
app:updatecommand for API-only Applications.y-yagi
-
Don't add bin/brakeman if brakeman is not in bundle when upgrading an application.
Etienne Barrié
-
Remove PWA views and routes if its an API only project.
Jean Boussier
-
Simplify generated Puma configuration
DHH, Rafael Mendonça França
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
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Gracefully handle
Timeout.timeoutfiring during connection configuration.Use of
Timeout.timeoutcould result in improperly initialized database connection.This could lead to a partially configured connection being used, resulting in various exceptions, the most common being with the PostgreSQLAdapter raising
undefined methodkey?' for nilorTypeError: wrong argument type nil (expected PG::TypeMap)`.Jean Boussier
-
Fix error handling during connection configuration.
Active Record wasn't properly handling errors during the connection configuration phase. This could lead to a partially configured connection being used, resulting in various exceptions, the most common being with the PostgreSQLAdapter raising
undefined methodkey?' for nilorTypeError: wrong argument type nil (expected PG::TypeMap)`.Jean Boussier
-
Fix prepared statements on mysql2 adapter.
Jean Boussier
-
Fix a race condition in
ActiveRecord::Base#method_missingwhen lazily defining attributes.If multiple thread were concurrently triggering attribute definition on the same model, it could result in a
NoMethodErrorbeing raised.Jean Boussier
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
-
Fixed compatibility with
redisgem5.4.1Jean Boussier
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Guides
- No changes.
Active Support
- No changes.
Active Model
-
Fix regression in
alias_attributeto work with user defined methods.alias_attributewould wrongly assume the attribute accessor was generated by Active Model.class Person include ActiveModel::AttributeMethods define_attribute_methods :name attr_accessor :name alias_attribute :full_name, :name end person.full_name # => NoMethodError: undefined method `attribute' for an instance of PersonJean Boussier
Active Record
-
Fix marshalling of unsaved associated records in 7.1 format.
The 7.1 format would only marshal associated records if the association was loaded. But associations that would only contain unsaved records would be skipped.
Jean Boussier
-
Fix an issue where
.left_outer_joinsused with multiple associations that have the same child association but different parents does not join all parents.Previously, using
.left_outer_joinswith the same child association would only join one of the parents.Now it will correctly join both parents.
Fixes #41498.
Garrett Blehm
-
Ensure
ActiveRecord::Encryption.configis always ready before access.Previously,
ActiveRecord::Encryptionconfiguration was deferred untilActiveRecord::Basewas loaded. Therefore, accessingActiveRecord::Encryption.configproperties beforeActiveRecord::Basewas loaded would give incorrect results.ActiveRecord::Encryptionnow has its own loading hook so that its configuration is set as soon as needed.When
ActiveRecord::Baseis loaded, even lazily, it in turn triggers the loading ofActiveRecord::Encryption, thus preserving the original behavior of having its config ready before any use ofActiveRecord::Base.Maxime Réty
-
Add
TimeZoneConverter#==method, so objects will be properly compared by their type, scale, limit & precision.Address #52699.
Ruy Rocha
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Guides
- No changes.
Active Support
-
Improve compatibility for
ActiveSupport::BroadcastLogger.Máximo Mussini
-
Pass options along to write_entry in handle_expired_entry method.
Graham Cooper
-
Fix Active Support configurations deprecations.
fatkodima
-
Fix teardown callbacks.
Tristan Starck
-
BacktraceCleanersilence core internal methods by default.Jean Boussier
-
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
-
Work around a Ruby bug that can cause a VM crash.
This would happen if using
TaggerLoggerwith a Proc formatter on which you calledobject_id.[BUG] Object ID seen, but not in mapping table: procJean Boussier
-
Fix
ActiveSupport::Notifications.publish_eventto preserve units.This solves the incorrect reporting of time spent running Active Record asynchronous queries (by a factor
1000).Jean Boussier
Active Model
- No changes.
Active Record
-
Allow to eager load nested nil associations.
fatkodima
-
Fix
create_tablewith:auto_incrementoption for MySQL adapter.fatkodima
-
Don't load has_one associations during autosave.
Eugene Kenny
-
Fix migration ordering for
bin/rails db:prepareacross databases.fatkodima
-
Fix
alias_attributeto ignore methods defined in parent classes.Jean Boussier
-
Fix a performance regression in attribute methods.
Jean Boussier
-
Fix Active Record configs variable shadowing.
Joel Lubrano
-
Fix running migrations on other databases when
database_tasks: falseon primary.fatkodima
-
Fix non-partial inserts for models with composite identity primary keys.
fatkodima
-
Fix
ActiveRecord::Relation#touch_allwith custom attribute aliased as attribute for update.fatkodima
-
Fix a crash when an Executor wrapped fork exit.
Joé Dupuis
-
Fix
destroy_asyncjob for owners with composite primary keys.fatkodima
-
Ensure pre-7.1 migrations use legacy index names when using
rename_table.fatkodima
-
Allow
primary_key:association option to be composite.Nikita Vasilevsky
-
Do not try to alias on key update when raw SQL is supplied.
Gabriel Amaral
-
Memoize
key_providerfromkeyor deterministickey_providerif any.Rosa Gutierrez
-
Fix
upsertwarning for MySQL.fatkodima
-
Fix predicate builder for polymorphic models referencing models with composite primary keys.
fatkodima
-
Fix
update_all/delete_allon CPK model relation with join subquery.Nikita Vasilevsky
-
Remove memoization to accept
key_provideroverridden bywith_encryption_context.John Hawthorn
-
Raise error for Trilogy when prepared_statements is true.
Trilogy doesn't currently support prepared statements. The error that applications would see is a
StatementInvaliderror. This doesn't quite point you to the fact this isn't supported. So raise a more appropriate error pointing to what to change.Eileen M. Uchitelle
-
Fix loading schema cache when all databases have disabled database tasks.
fatkodima
-
Always request
primary_keyinRETURNINGif no other columns requested.Nikita Vasilevsky
-
Handle records being loaded with Marshal without triggering schema load
When using the old marshalling format for Active Record and loading a serialized instance, it didn't trigger loading the schema and defining attribute methods.
Jean Boussier
-
Prevent some constant redefinition warnings when defining
inheritedon models.Adrian Hirt
-
Fix a memory perfomance regression in attribute methods.
Attribute methods used much more memory and were slower to define than they should have been.
Jean Boussier
-
Fix an issue that could cause database connection leaks.
If Active Record successfully connected to the database, but then failed to read the server informations, the connection would be leaked until the Ruby garbage collector triggers.
Jean Boussier
-
Fix an issue where the IDs reader method did not return expected results for preloaded associations in models using composite primary keys.
Jay Ang
-
PostgreSQL
Cidr#change?detects the address prefix change.Taketo Takashima
-
Fix Active Record serialization to not include instantiated but not loaded associations
Jean Boussier, Ben Kyriakou
-
Allow
Sqlite3Adapterto usesqlite3gem version2.xMike Dalessio
-
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
-
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 behaviour 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
-
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
-
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
-
Fix counter caches when the foreign key is composite.
If the model holding the counter cache had a composite primary key, inserting a dependent record would fail with an
ArgumentErrorExpected corresponding value for...fatkodima
-
Fix loading of schema cache for multiple databases.
Before this change, if you have multiple databases configured in your application, and had schema cache present, Rails would load the same cache to all databases.
Rafael Mendonça França
-
Fix eager loading of composite primary key associations.
relation.eager_load(:other_model)could load the wrong records ifother_modelhad a composite primary key.Nikita Vasilevsky
-
Fix async queries returning a doubly wrapped result when hitting the query cache.
fatkodima
-
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
t.references.Hartley McGuire
Action View
-
Action View Test Case
renderedmemoization.Sean Doyle
-
Restore the ability for templates to return any kind of object and not just strings
Jean Boussier
-
Fix threading issue with strict locals.
Robert Fletcher
Action Pack
-
Resolve deprecation warning in latest
selenium-webdriver.Earlopain
-
Don't preload Selenium browser when remote.
Noah Horton
-
Fix crash for invalid Content-Type in ShowExceptions middleware.
Earlopain
-
Fix inconsistent results of
params.deep_transform_keys.Iago Pimenta
-
Do not report rendered errors except 500.
Nikita Vasilevsky
-
Improve routes source location detection.
Jean Boussier
-
Fix
Request#raw_postraisingNoMethodErrorwhenrack.inputisnil.Hartley McGuire
-
Fix url generation in nested engine when script name is empty.
zzak
-
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
-
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é
-
Fix
ActionDispatch::Executormiddleware to report errors handled byActionDispatch::ShowExceptionsIn the default production environment,
ShowExceptionsrescues uncaught errors and returns a response. Because of this the executor wouldn't report production errors with the default Rails configuration.Jean Boussier
Active Job
-
Register autoload for
ActiveJob::Arguments.Rafael Mendonça França
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Fixes race condition for multiple preprocessed video variants.
Justin Searls
Action Mailbox
- No changes.
Action Text
-
Strip
contentattribute if the key is present but the value is emptyJeremy Green
-
Only sanitize
contentattribute when present in attachments.Petrik de Heus
Railties
-
Preserve
--asset-pipeline propshaftwhen runningapp:update.Zacharias Knudsen
-
Allow string keys for SQLCommenter.
Ngan Pham
-
Fix derived foreign key to return correctly when association id is part of query constraints.
Varun Sharma
-
Show warning for
secret_key_basein development too.fatkodima
-
Fix sanitizer vendor configuration in 7.1 defaults.
In apps where
rails-html-sanitizerwas not eagerly loaded, the sanitizer default could end up being Rails::HTML4::Sanitizer when it should be set toRails::HTML5::Sanitizer.Mike Dalessio, Rafael Mendonça França
-
Revert the use of
Concurrent.physical_processor_countin default Puma configWhile for many people this saves one config to set, for many others using a shared hosting solution, this cause the default configuration to spawn way more workers than reasonable.
There is unfortunately no reliable way to detect how many cores an application can realistically use, and even then, assuming the application should use all the machine resources is often wrong.
Jean Boussier
Active Support
-
Handle nil
backtrace_locationsinActiveSupport::SyntaxErrorProxy.Eugene Kenny
-
Fix
ActiveSupport::JSON.encodeto prevent duplicate keys.If the same key exist in both String and Symbol form it could lead to the same key being emitted twice.
Manish Sharma
-
Fix
ActiveSupport::Cache::Store#read_multiwhen using a cache namespace and local cache strategy.Mark Oleson
-
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 behaviour is to return results in a system timezone.
Aleksei Chernenkov
-
Fix
:unless_existoption forMemoryStore#write(et al) when using a cache namespace.S. Brent Faulkner
-
Fix ActiveSupport::Deprecation to handle blaming generated code.
Jean Boussier, fatkodima
Active Model
- No changes.
Active Record
-
Fix Migrations with versions older than 7.1 validating options given to
add_reference.Hartley McGuire
-
Ensure
reloadsets correct owner for each association.Dmytro Savochkin
-
Fix view runtime for controllers with async queries.
fatkodima
-
Fix
load_asyncto work with query cache.fatkodima
-
Fix polymorphic
belongs_toto correctly use parent'squery_constraints.fatkodima
-
Fix
Preloaderto not generate a query for already loaded association withquery_constraints.fatkodima
-
Fix multi-database polymorphic preloading with equivalent table names.
When preloading polymorphic associations, if two models pointed to two tables with the same name but located in different databases, the preloader would only load one.
Ari Summer
-
Fix
encrypted_attribute?to take into account context properties passed toencrypts.Maxime Réty
-
Fix
find_byto work correctly in presence of composite primary keys.fatkodima
-
Fix async queries sometimes returning a raw result if they hit the query cache.
ShipPart.async_countcould return a raw integer rather than a Promise if it found the result in the query cache.fatkodima
-
Fix
Relation#transactionto not apply a default scope.The method was incorrectly setting a default scope around its block:
Post.where(published: true).transaction do Post.count # SELECT COUNT(*) FROM posts WHERE published = FALSE; endJean Boussier
-
Fix calling
async_pluckon anonerelation.Model.none.async_pluck(:id)was returning a naked value instead of a promise.Jean Boussier
-
Fix calling
load_asyncon anonerelation.Model.none.load_asyncwas returning a broken result.Lucas Mazza
-
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
-
Fix
has_secure_tokencalls the setter method on initialize.Abeid Ahmed
-
Allow using
object_idas a database column name. It was available before rails 7.1 and may be used as a part of polymorphic relationship toobjectwhereobjectcan be any other database record.Mikhail Doronin
-
Fix
rails db:create:allto not touch databases before they are created.fatkodima
Action View
-
Better handle SyntaxError in Action View.
Mario Caropreso
-
Fix
word_wrapwith empty string.Jonathan Hefner
-
Rename
ActionView::TestCase::Behavior::ContenttoActionView::TestCase::Behavior::RenderedViewContent.Make
RenderedViewContentinherit fromString. Make private API with:nodoc:.Sean Doyle
-
Fix detection of required strict locals.
Further fix
render @collectioncompatibility with strict localsJean Boussier
Action Pack
-
Fix including
Rails.application.routes.url_helpersdirectly in anActiveSupport::Concern.Jonathan Hefner
-
Fix system tests when using a Chrome binary that has been downloaded by Selenium.
Jonathan Hefner
Active Job
-
Do not trigger immediate loading of
ActiveJob::Basewhen loadingActiveJob::TestHelper.Maxime Réty
-
Preserve the serialized timezone when deserializing
ActiveSupport::TimeWithZonearguments.Joshua Young
-
Fix ActiveJob arguments serialization to correctly serialize String subclasses having custom serializers.
fatkodima
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
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
-
Fix direct upload forms when submit button contains nested elements.
Marc Köhlbrugge
-
When using the
preprocessed: trueoption, avoid enqueuing transform jobs for blobs that are not representable.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
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Make sure
config.after_routes_loadedhook runs on boot.Rafael Mendonça França
-
Fix
config.log_levelnot being respected when using aBroadcastLoggerÉdouard Chin
-
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
-
The
bin/rails app:templatecommand will no longer add potentially unwanted gem platforms viabundle lock --add-platform=...commands.Jonathan Hefner
Active Support
-
Fix
:expires_inoption forRedisCacheStore#write_multi.fatkodima
-
Fix deserialization of non-string "purpose" field in Message serializer
Jacopo Beschi
-
Prevent global cache options being overwritten when setting dynamic options inside a
ActiveSupport::Cache::Store#fetchblock.Yasha Krasnou
-
Fix missing
requireresulting inNoMethodErrorwhen runningbin/rails secrets:showorbin/rails secrets:edit.Stephen Ierodiaconou
-
Ensure
{down,up}case_firstreturns non-frozen string.Jonathan Hefner
-
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
ActiveSupport::Cacheto handle outdated Marshal payload from Rails 6.1 format.Active Support's Cache is supposed to treat a Marshal payload that can no longer be deserialized as a cache miss. It fail to do so for compressed payload in the Rails 6.1 legacy format.
Jean Boussier
-
Fix
OrderedOptions#digfor array indexes.fatkodima
-
Fix time travel helpers to work when nested using with separate classes.
fatkodima
-
Fix
delete_matchedfor file cache store to work with keys longer than the max filename size.fatkodima and Jonathan Hefner
-
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
Active Model
-
Make
==(other)method of AttributeSet safe.Dmitry Pogrebnoy
Active Record
-
Fix renaming primary key index when renaming a table with a UUID primary key in PostgreSQL.
fatkodima
-
Fix
where(field: values)queries whenfieldis a serialized attribute (for example, whenfieldusesActiveRecord::Base.serializeor is a JSON column).João Alves
-
Prevent marking broken connections as verified.
Daniel Colson
-
Don't mark Float::INFINITY as changed when reassigning it
When saving a record with a float infinite value, it shouldn't mark as changed
Maicol Bentancor
-
ActiveRecord::Base.table_namenow returnsnilinstead of raising "undefined methodabstract_class?for Object:Class".a5-stable
-
Fix upserting for custom
:on_duplicateand:unique_byconsisting of all inserts keys.fatkodima
-
Fixed an issue where saving a record could innappropriately
dupits attributes.Jonathan Hefner
-
Dump schema only for a specific db for rollback/up/down tasks for multiple dbs.
fatkodima
-
Fix
NoMethodErrorwhen casting a PostgreSQLmoneyvalue that uses a comma as its radix point and has no leading currency symbol. For example, when casting"3,50".Andreas Reischuck and Jonathan Hefner
-
Re-enable support for using
enumwith non-column-backed attributes. Non-column-backed attributes must be previously declared with an explicit type. For example:class Post < ActiveRecord::Base attribute :topic, :string enum topic: %i[science tech engineering math] endJonathan Hefner
-
Raise on
foreign_key:being passed as an array in associationsNikita Vasilevsky
-
Return back maximum allowed PostgreSQL table name to 63 characters.
fatkodima
-
Fix detecting
IDENTITYcolumns for PostgreSQL < 10.fatkodima
Action View
-
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 bundlersHartley McGuire, Ryunosuke Sato
-
Fix the
captureview helper compatibility with HAML and SlimWhen a blank string was captured in HAML or Slim (and possibly other template engines) it would instead return the entire buffer.
Jean Boussier
Action Pack
-
Fix a race condition that could cause a
Text file busy - chromedrivererror with parallel system testsMatt Brictson
-
Fix
StrongParameters#extract_valueto include blank valuesOtherwise composite parameters may not be parsed correctly when one of the component is blank.
fatkodima, Yasha Krasnou, Matthias Eiglsperger
-
Add
raccas a dependency since it will become a bundled gem in Ruby 3.4.0Hartley McGuire
-
Support handling Enumerator for non-buffered responses.
Zachary Scott
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
-
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
-
Fix running
db:system:changewhen app has no Dockerfile.Hartley McGuire
-
If you accessed
config.eager_load_pathsand friends, later changes toconfig.pathswere not reflected in the expected auto/eager load paths. Now, they are.This bug has been latent since Rails 3.
Fixes #49629.
Xavier Noria
Active Support
-
Add support for keyword arguments when delegating calls to custom loggers from
ActiveSupport::BroadcastLogger.Jenny Shen
-
NumberHelper: handle objects respondingto_d.fatkodima
-
Fix RedisCacheStore to properly set the TTL when incrementing or decrementing.
This bug was only impacting Redis server older than 7.0.
Thomas Countz
-
Fix MemoryStore to prevent race conditions when incrementing or decrementing.
Pierre Jambet
Active Model
- No changes.
Active Record
-
Fix auto populating IDENTITY columns for PostgreSQL.
fatkodima
-
Fix "ArgumentError: wrong number of arguments (given 3, expected 2)" when down migrating
rename_tablein older migrations.fatkodima
-
Do not require the Action Text, Active Storage and Action Mailbox tables to be present when running when running test on CI.
Rafael Mendonça França
Action View
-
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
Action Pack
- No changes.
Active Job
-
Don't log enqueuing details when the job wasn't enqueued.
Dustin Brown
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Ensures the Rails generated Dockerfile uses correct ruby version and matches Gemfile.
Abhay Nikam
Active Support
-
Fix
AS::MessagePackwithENV["RAILS_MAX_THREADS"].Jonathan Hefner
-
Add a new public API for broadcasting logs
This feature existed for a while but was until now a private API. Broadcasting log allows to send log message to difference sinks (STDOUT, a file ...) and is used by default in the development environment to write logs both on STDOUT and in the "development.log" file.
Basic usage:
stdout_logger = Logger.new(STDOUT) file_logger = Logger.new("development.log") broadcast = ActiveSupport::BroadcastLogger.new(stdout_logger, file_logger) broadcast.info("Hello!") # The "Hello!" message is written on STDOUT and in the log file.Adding other sink(s) to the broadcast:
broadcast = ActiveSupport::BroadcastLogger.new broadcast.broadcast_to(Logger.new(STDERR))Remove a sink from the broadcast:
stdout_logger = Logger.new(STDOUT) broadcast = ActiveSupport::BroadcastLogger.new(stdout_logger) broadcast.stop_broadcasting_to(stdout_logger)Edouard Chin
-
Fix Range#overlap? not taking empty ranges into account on Ruby < 3.3
Nobuyoshi Nakada, Shouichi Kamiya, Hartley McGuire
-
Use Ruby 3.3 Range#overlap? if available
Yasuo Honda
-
Add
bigdecimalas Active Support dependency that is a bundled gem candidate for Ruby 3.4.bigdecimal3.1.4 or higher version will be installed. Ruby 2.7 and 3.0 users who wantbigdecimalversion 2.0.0 or 3.0.0 behavior as a default gem, pin thebigdecimalversion in your application Gemfile.Koichi ITO
-
Add
drb,mutex_mandbase64that are bundled gem candidates for Ruby 3.4Yasuo Honda
-
When using cache format version >= 7.1 or a custom serializer, expired and version-mismatched cache entries can now be detected without deserializing their values.
Jonathan Hefner
-
Make all cache stores return a boolean for
#deletePreviously the
RedisCacheStore#deletewould return1if the entry exists and0otherwise. Now it returns true if the entry exists and false otherwise, just like the other stores.The
FileStorewould returnnilif the entry doesn't exists and returnsfalsenow as well.Petrik de Heus
-
Active Support cache stores now support replacing the default compressor via a
:compressoroption. The specified compressor must respond todeflateandinflate. For example:module MyCompressor def self.deflate(string) # compression logic... end def self.inflate(compressed) # decompression logic... end end config.cache_store = :redis_cache_store, { compressor: MyCompressor }Jonathan Hefner
-
Active Support cache stores now support a
:serializeroption. Similar to the:coderoption, serializers must respond todumpandload. However, serializers are only responsible for serializing a cached value, whereas coders are responsible for serializing the entireActiveSupport::Cache::Entryinstance. Additionally, the output from serializers can be automatically compressed, whereas coders are responsible for their own compression.Specifying a serializer instead of a coder also enables performance optimizations, including the bare string optimization introduced by cache format version 7.1.
The
:serializerand:coderoptions are mutually exclusive. Specifying both will raise anArgumentError.Jonathan Hefner
-
Fix
ActiveSupport::Inflector.humanize(nil)raisingNoMethodError: undefined method `end_with?' for nil:NilClass.James Robinson
-
Don't show secrets for
ActiveSupport::KeyGenerator#inspect.Before:
ActiveSupport::KeyGenerator.new(secret).inspect "#<ActiveSupport::KeyGenerator:0x0000000104888038 ... @secret=\"\\xAF\\bFh]LV}q\\nl\\xB2U\\xB3 ... >"After:
ActiveSupport::KeyGenerator::Aes256Gcm(secret).inspect "#<ActiveSupport::KeyGenerator:0x0000000104888038>"Petrik de Heus
-
Improve error message when EventedFileUpdateChecker is used without a compatible version of the Listen gem
Hartley McGuire
-
Add
:reportbehavior for DeprecationSetting
config.active_support.deprecation = :reportuses the error reporter to report deprecation warnings toActiveSupport::ErrorReporter.Deprecations are reported as handled errors, with a severity of
:warning.Useful to report deprecations happening in production to your bug tracker.
Étienne Barrié
-
Rename
Range#overlaps?to#overlap?and add alias for backwards compatibilityChristian Schmidt
-
Fix
EncryptedConfigurationreturning incorrect values for someHashmethodsHartley McGuire
-
Don't show secrets for
MessageEncryptor#inspect.Before:
ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm").inspect "#<ActiveSupport::MessageEncryptor:0x0000000104888038 ... @secret=\"\\xAF\\bFh]LV}q\\nl\\xB2U\\xB3 ... >"After:
ActiveSupport::MessageEncryptor.new(secret, cipher: "aes-256-gcm").inspect "#<ActiveSupport::MessageEncryptor:0x0000000104888038>"Petrik de Heus
-
Don't show contents for
EncryptedConfiguration#inspect.Before:
Rails.application.credentials.inspect "#<ActiveSupport::EncryptedConfiguration:0x000000010d2b38e8 ... @config={:secret=>\"something secret\"} ... @key_file_contents=\"915e4ea054e011022398dc242\" ...>"After:
Rails.application.credentials.inspect "#<ActiveSupport::EncryptedConfiguration:0x000000010d2b38e8>"Petrik de Heus
-
ERB::Util.html_escape_oncealways returns anhtml_safestring.This method previously maintained the
html_safe?property of a string on the return value. Because this string has been escaped, however, not marking it ashtml_safecauses entities to be double-escaped.As an example, take this view snippet:
<p><%= html_escape_once("this & that & the other") %></p>Before this change, that would be double-escaped and render as:
<p>this &amp; that &amp; the other</p>After this change, it renders correctly as:
<p>this & that & the other</p>Fixes #48256
Mike Dalessio
-
Deprecate
SafeBuffer#clone_empty.This method has not been used internally since Rails 4.2.0.
Mike Dalessio
-
MessageEncryptor,MessageVerifier, andconfig.active_support.message_serializernow accept:message_packand:message_pack_allow_marshalas serializers. These serializers require themsgpackgem (>= 1.7.0).The Message Pack format can provide improved performance and smaller payload sizes. It also supports round-tripping some Ruby types that are not supported by JSON. For example:
verifier = ActiveSupport::MessageVerifier.new("secret") data = [{ a: 1 }, { b: 2 }.with_indifferent_access, 1.to_d, Time.at(0, 123)] message = verifier.generate(data) # BEFORE with config.active_support.message_serializer = :json verifier.verified(message) # => [{"a"=>1}, {"b"=>2}, "1.0", "1969-12-31T18:00:00.000-06:00"] verifier.verified(message).map(&:class) # => [Hash, Hash, String, String] # AFTER with config.active_support.message_serializer = :message_pack verifier.verified(message) # => [{:a=>1}, {"b"=>2}, 0.1e1, 1969-12-31 18:00:00.000123 -0600] verifier.verified(message).map(&:class) # => [Hash, ActiveSupport::HashWithIndifferentAccess, BigDecimal, Time]The
:message_packserializer can fall back to deserializing withActiveSupport::JSONwhen necessary, and the:message_pack_allow_marshalserializer can fall back to deserializing withMarshalas well asActiveSupport::JSON. Additionally, the:marshal,:json, and:json_allow_marshalserializers can now fall back to deserializing withActiveSupport::MessagePackwhen necessary. These behaviors ensure old messages can still be read so that migration is easier.Jonathan Hefner
-
A new
7.1cache format is available which includes an optimization for bare string values such as view fragments.The
7.1cache format is used by default for new apps, and existing apps can enable the format by settingconfig.load_defaults 7.1or by settingconfig.active_support.cache_format_version = 7.1inconfig/application.rbor aconfig/environments/*.rbfile.Cache entries written using the
6.1or7.0cache formats can be read when using the7.1format. To perform a rolling deploy of a Rails 7.1 upgrade, wherein servers that have not yet been upgraded must be able to read caches from upgraded servers, leave the cache format unchanged on the first deploy, then enable the7.1cache format on a subsequent deploy.Jonathan Hefner
-
Active Support cache stores can now use a preconfigured serializer based on
ActiveSupport::MessagePackvia the:serializeroption:config.cache_store = :redis_cache_store, { serializer: :message_pack }The
:message_packserializer can reduce cache entry sizes and improve performance, but requires themsgpackgem (>= 1.7.0).The
:message_packserializer can read cache entries written by the default serializer, and the default serializer can now read entries written by the:message_packserializer. These behaviors make it easy to migrate between serializer without invalidating the entire cache.Jonathan Hefner
-
Object#deep_dupno longer duplicate named classes and modules.Before:
hash = { class: Object, module: Kernel } hash.deep_dup # => {:class=>#<Class:0x00000001063ffc80>, :module=>#<Module:0x00000001063ffa00>}After:
hash = { class: Object, module: Kernel } hash.deep_dup # => {:class=>Object, :module=>Kernel}Jean Boussier
-
Consistently raise an
ArgumentErrorif theActiveSupport::Cachekey is blank.Joshua Young
-
Deprecate usage of the singleton
ActiveSupport::Deprecation.All usage of
ActiveSupport::Deprecationas a singleton is deprecated, the most common one beingActiveSupport::Deprecation.warn. Gem authors should now create their own deprecator (ActiveSupport::Deprecationobject), and use it to emit deprecation warnings.Calling any of the following without specifying a deprecator argument is also deprecated:
- Module.deprecate
- deprecate_constant
- DeprecatedObjectProxy
- DeprecatedInstanceVariableProxy
- DeprecatedConstantProxy
- deprecation-related test assertions
Use of
ActiveSupport::Deprecation.silenceand configuration methods likebehavior=,disallowed_behavior=,disallowed_warnings=should now be aimed at the application's deprecators.Rails.application.deprecators.silence do # code that emits deprecation warnings endIf your gem has a Railtie or Engine, it's encouraged to add your deprecator to the application's deprecators, that way the deprecation related configuration options will apply to it as well, e.g.
config.active_support.report_deprecationsset tofalsein the production environment will also disable your deprecator.initializer "my_gem.deprecator" do |app| app.deprecators[:my_gem] = MyGem.deprecator endÉtienne Barrié
-
Add
Object#withto set and restore public attributes around a blockclient.timeout # => 5 client.with(timeout: 1) do client.timeout # => 1 end client.timeout # => 5Jean Boussier
-
Remove deprecated support to generate incorrect RFC 4122 UUIDs when providing a namespace ID that is not one of the constants defined on
Digest::UUID.Rafael Mendonça França
-
Deprecate
config.active_support.use_rfc4122_namespaced_uuids.Rafael Mendonça França
-
Remove implicit conversion of objects into
StringbyActiveSupport::SafeBuffer.Rafael Mendonça França
-
Remove deprecated
active_support/core_ext/range/include_time_with_zonefile.Rafael Mendonça França
-
Deprecate
config.active_support.remove_deprecated_time_with_zone_name.Rafael Mendonça França
-
Remove deprecated override of
ActiveSupport::TimeWithZone.name.Rafael Mendonça França
-
Deprecate
config.active_support.disable_to_s_conversion.Rafael Mendonça França
-
Remove deprecated option to passing a format to
#to_sinArray,Range,Date,DateTime,Time,BigDecimal,Floatand,Integer.Rafael Mendonça França
-
Remove deprecated
ActiveSupport::PerThreadRegistry.Rafael Mendonça França
-
Remove deprecated override of
Enumerable#sum.Rafael Mendonça França
-
Deprecated initializing a
ActiveSupport::Cache::MemCacheStorewith an instance ofDalli::Client.Deprecate the undocumented option of providing an already-initialized instance of
Dalli::ClienttoActiveSupport::Cache::MemCacheStore. Such clients could be configured with unrecognized options, which could lead to unexpected behavior. Instead, provide addresses as documented.aledustet
-
Stub
Time.new()inTimeHelpers#travel_totravel_to Time.new(2004, 11, 24) do # Inside the `travel_to` block `Time.new` is stubbed assert_equal 2004, Time.new.year endfatkodima
-
Raise
ActiveSupport::MessageEncryptor::InvalidMessagefromActiveSupport::MessageEncryptor#decrypt_and_verifyregardless of cipher. Previously, when aMessageEncryptorwas using a non-AEAD cipher such as AES-256-CBC, a corrupt or tampered message would raiseActiveSupport::MessageVerifier::InvalidSignature. Now, all ciphers raise the same error:encryptor = ActiveSupport::MessageEncryptor.new("x" * 32, cipher: "aes-256-gcm") message = encryptor.encrypt_and_sign("message") encryptor.decrypt_and_verify(message.next) # => raises ActiveSupport::MessageEncryptor::InvalidMessage encryptor = ActiveSupport::MessageEncryptor.new("x" * 32, cipher: "aes-256-cbc") message = encryptor.encrypt_and_sign("message") encryptor.decrypt_and_verify(message.next) # BEFORE: # => raises ActiveSupport::MessageVerifier::InvalidSignature # AFTER: # => raises ActiveSupport::MessageEncryptor::InvalidMessageJonathan Hefner
-
Support
niloriginal values when usingActiveSupport::MessageVerifier#verify. Previously,MessageVerifier#verifydid not work withniloriginal values, though bothMessageVerifier#verifiedandMessageEncryptor#decrypt_and_verifydo:encryptor = ActiveSupport::MessageEncryptor.new(secret) message = encryptor.encrypt_and_sign(nil) encryptor.decrypt_and_verify(message) # => nil verifier = ActiveSupport::MessageVerifier.new(secret) message = verifier.generate(nil) verifier.verified(message) # => nil verifier.verify(message) # BEFORE: # => raises ActiveSupport::MessageVerifier::InvalidSignature # AFTER: # => nilJonathan Hefner
-
Maintain
html_safe?on html_safe strings when sliced withslice,slice!, orchrmethod.Previously,
html_safe?was only maintained when the html_safe strings were sliced with[]method. Now,slice,slice!, andchrmethods will maintainhtml_safe?like[]method.string = "<div>test</div>".html_safe string.slice(0, 1).html_safe? # => true string.slice!(0, 1).html_safe? # => true # maintain html_safe? after the slice! string.html_safe? # => true string.chr.html_safe? # => trueMichael Go
-
Add
Object#in?support for open ranges.assert Date.today.in?(..Date.tomorrow) assert_not Date.today.in?(Date.tomorrow..)Ignacio Galindo
-
config.i18n.raise_on_missing_translations = truenow raises on any missing translation.Previously it would only raise when called in a view or controller. Now it will raise anytime
I18n.tis provided an unrecognised key.If you do not want this behaviour, you can customise the i18n exception handler. See the upgrading guide or i18n guide for more information.
Alex Ghiculescu
-
ActiveSupport::CurrentAttributesnow raises if a restricted attribute name is used.Attributes such as
setandresetcannot be used as they clash with theCurrentAttributespublic API.Alex Ghiculescu
-
HashWithIndifferentAccess#transform_keysnow takes a Hash argument, just as Ruby'sHash#transform_keysdoes.Akira Matsuda
-
delegatenow defines method with proper arity when delegating to a Class. With this change, it defines faster method (3.5x faster with no argument). However, in order to gain this benefit, the delegation target method has to be defined before declaring the delegation.# This defines 3.5 times faster method than before class C def self.x() end delegate :x, to: :class end class C # This works but silently falls back to old behavior because # `delegate` cannot find the definition of `x` delegate :x, to: :class def self.x() end endAkira Matsuda
-
assert_differencemessage now includes what changed.This makes it easier to debug non-obvious failures.
Before:
"User.count" didn't change by 32. Expected: 1611 Actual: 1579After:
"User.count" didn't change by 32, but by 0. Expected: 1611 Actual: 1579Alex Ghiculescu
-
Add ability to match exception messages to
assert_raisesassertionInstead of this
error = assert_raises(ArgumentError) do perform_service(param: 'exception') end assert_match(/incorrect param/i, error.message)you can now write this
assert_raises(ArgumentError, match: /incorrect param/i) do perform_service(param: 'exception') endfatkodima
-
Add
Rails.env.local?shorthand forRails.env.development? || Rails.env.test?.DHH
-
ActiveSupport::Testing::TimeHelpersnow accepts namedwith_usecargument tofreeze_time,travel, andtravel_tomethods. Passing true prevents truncating the destination time withchange(usec: 0).KevSlashNull, and serprex
-
ActiveSupport::CurrentAttributes.resetsnow accepts a method nameThe block API is still the recommended approach, but now both APIs are supported:
class Current < ActiveSupport::CurrentAttributes resets { Time.zone = nil } resets :clear_time_zone endAlex Ghiculescu
-
Ensure
ActiveSupport::Testing::Isolation::Forkingcloses pipesPreviously,
Forking.run_in_isolationopened two ends of a pipe. The fork process closed the read end, wrote to it, and then terminated (which presumably closed the file descriptors on its end). The parent process closed the write end, read from it, and returned, never closing the read end.This resulted in an accumulation of open file descriptors, which could cause errors if the limit is reached.
Sam Bostock
-
Fix
Time#changeandTime#advancefor times around the end of Daylight Saving Time.Previously, when
Time#changeorTime#advanceconstructed a time inside the final stretch of Daylight Saving Time (DST), the non-DST offset would always be chosen for local times:# DST ended just before 2021-11-07 2:00:00 AM in US/Eastern. ENV["TZ"] = "US/Eastern" time = Time.local(2021, 11, 07, 00, 59, 59) + 1 # => 2021-11-07 01:00:00 -0400 time.change(day: 07) # => 2021-11-07 01:00:00 -0500 time.advance(seconds: 0) # => 2021-11-07 01:00:00 -0500 time = Time.local(2021, 11, 06, 01, 00, 00) # => 2021-11-06 01:00:00 -0400 time.change(day: 07) # => 2021-11-07 01:00:00 -0500 time.advance(days: 1) # => 2021-11-07 01:00:00 -0500And the DST offset would always be chosen for times with a
TimeZoneobject:Time.zone = "US/Eastern" time = Time.new(2021, 11, 07, 02, 00, 00, Time.zone) - 3600 # => 2021-11-07 01:00:00 -0500 time.change(day: 07) # => 2021-11-07 01:00:00 -0400 time.advance(seconds: 0) # => 2021-11-07 01:00:00 -0400 time = Time.new(2021, 11, 8, 01, 00, 00, Time.zone) # => 2021-11-08 01:00:00 -0500 time.change(day: 07) # => 2021-11-07 01:00:00 -0400 time.advance(days: -1) # => 2021-11-07 01:00:00 -0400Now,
Time#changeandTime#advancewill choose the offset that matches the original time's offset when possible:ENV["TZ"] = "US/Eastern" time = Time.local(2021, 11, 07, 00, 59, 59) + 1 # => 2021-11-07 01:00:00 -0400 time.change(day: 07) # => 2021-11-07 01:00:00 -0400 time.advance(seconds: 0) # => 2021-11-07 01:00:00 -0400 time = Time.local(2021, 11, 06, 01, 00, 00) # => 2021-11-06 01:00:00 -0400 time.change(day: 07) # => 2021-11-07 01:00:00 -0400 time.advance(days: 1) # => 2021-11-07 01:00:00 -0400 Time.zone = "US/Eastern" time = Time.new(2021, 11, 07, 02, 00, 00, Time.zone) - 3600 # => 2021-11-07 01:00:00 -0500 time.change(day: 07) # => 2021-11-07 01:00:00 -0500 time.advance(seconds: 0) # => 2021-11-07 01:00:00 -0500 time = Time.new(2021, 11, 8, 01, 00, 00, Time.zone) # => 2021-11-08 01:00:00 -0500 time.change(day: 07) # => 2021-11-07 01:00:00 -0500 time.advance(days: -1) # => 2021-11-07 01:00:00 -0500Kevin Hall, Takayoshi Nishida, and Jonathan Hefner
-
Fix MemoryStore to preserve entries TTL when incrementing or decrementing
This is to be more consistent with how MemCachedStore and RedisCacheStore behaves.
Jean Boussier
-
Rails.error.handleandRails.error.recordfilter now by multiple error classes.Rails.error.handle(IOError, ArgumentError) do 1 + '1' # raises TypeError end 1 + 1 # TypeErrors are not IOErrors or ArgumentError, so this will *not* be handledMartin Spickermann
-
Class#subclassesandClass#descendantsnow automatically filter reloaded classes.Previously they could return old implementations of reloadable classes that have been dereferenced but not yet garbage collected.
They now automatically filter such classes like
DescendantTracker#subclassesandDescendantTracker#descendants.Jean Boussier
-
Rails.error.reportnow marks errors as reported to avoid reporting them twice.In some cases, users might want to report errors explicitly with some extra context before letting it bubble up.
This also allows to safely catch and report errors outside of the execution context.
Jean Boussier
-
Add
assert_error_reportedandassert_no_error_reportedAllows to easily asserts an error happened but was handled
report = assert_error_reported(IOError) do # ... end assert_equal "Oops", report.error.message assert_equal "admin", report.context[:section] assert_equal :warning, report.severity assert_predicate report, :handled?Jean Boussier
-
ActiveSupport::Deprecationbehavior callbacks can now receive the deprecator instance as an argument. This makes it easier for such callbacks to change their behavior based on the deprecator's state. For example, based on the deprecator'sdebugflag.3-arity and splat-args callbacks such as the following will now be passed the deprecator instance as their third argument:
->(message, callstack, deprecator) { ... }->(*args) { ... }->(message, *other_args) { ... }
2-arity and 4-arity callbacks such as the following will continue to behave the same as before:
->(message, callstack) { ... }->(message, callstack, deprecation_horizon, gem_name) { ... }->(message, callstack, *deprecation_details) { ... }
Jonathan Hefner
-
ActiveSupport::Deprecation#disallowed_warningsnow affects the instance on which it is configured.This means that individual
ActiveSupport::Deprecationinstances can be configured with their own disallowed warnings, and the globalActiveSupport::Deprecation.disallowed_warningsnow only affects the globalActiveSupport::Deprecation.warn.Before
ActiveSupport::Deprecation.disallowed_warnings = ["foo"] deprecator = ActiveSupport::Deprecation.new("2.0", "MyCoolGem") deprecator.disallowed_warnings = ["bar"] ActiveSupport::Deprecation.warn("foo") # => raise ActiveSupport::DeprecationException ActiveSupport::Deprecation.warn("bar") # => print "DEPRECATION WARNING: bar" deprecator.warn("foo") # => raise ActiveSupport::DeprecationException deprecator.warn("bar") # => print "DEPRECATION WARNING: bar"After
ActiveSupport::Deprecation.disallowed_warnings = ["foo"] deprecator = ActiveSupport::Deprecation.new("2.0", "MyCoolGem") deprecator.disallowed_warnings = ["bar"] ActiveSupport::Deprecation.warn("foo") # => raise ActiveSupport::DeprecationException ActiveSupport::Deprecation.warn("bar") # => print "DEPRECATION WARNING: bar" deprecator.warn("foo") # => print "DEPRECATION WARNING: foo" deprecator.warn("bar") # => raise ActiveSupport::DeprecationExceptionNote that global
ActiveSupport::Deprecationmethods such asActiveSupport::Deprecation.warnandActiveSupport::Deprecation.disallowed_warningshave been deprecated.Jonathan Hefner
-
Add italic and underline support to
ActiveSupport::LogSubscriber#colorPreviously, only bold text was supported via a positional argument. This allows for bold, italic, and underline options to be specified for colored logs.
info color("Hello world!", :red, bold: true, underline: true)Gannon McGibbon
-
Add
String#downcase_firstmethod.This method is the corollary of
String#upcase_first.Mark Schneider
-
thread_mattr_accessorwill call.dup.freezeon non-frozen default values.This provides a basic level of protection against different threads trying to mutate a shared default object.
Jonathan Hefner
-
Add
raise_on_invalid_cache_expiration_timeconfig toActiveSupport::Cache::StoreSpecifies if an
ArgumentErrorshould be raised ifRails.cachefetchorwriteare given an invalidexpires_atorexpires_intime.Options are
true, andfalse. Iffalse, the exception will be reported ashandledand logged instead. Defaults totrueifconfig.load_defaults >= 7.1.Trevor Turk
-
ActiveSupport::Cache:Store#fetchnow passes an options accessor to the block.It makes possible to override cache options:
Rails.cache.fetch("3rd-party-token") do |name, options| token = fetch_token_from_remote # set cache's TTL to match token's TTL options.expires_in = token.expires_in token endAndrii Gladkyi, Jean Boussier
-
defaultoption ofthread_mattr_accessornow applies through inheritance and also across new threads.Previously, the
defaultvalue provided was set only at the moment of defining the attribute writer, which would cause the attribute to be uninitialized in descendants and in other threads.Fixes #43312.
Thierry Deo
-
Redis cache store is now compatible with redis-rb 5.0.
Jean Boussier
-
Add
skip_nil:support toActiveSupport::Cache::Store#fetch_multi.Daniel Alfaro
-
Add
quartermethod to date/timeMatt Swanson
-
Fix
NoMethodErroron customActiveSupport::Deprecationbehavior.ActiveSupport::Deprecation.behavior=was supposed to accept any object that responds tocall, but in fact its internal implementation assumed that this object could respond toarity, so it was restricted to onlyProcobjects.This change removes this
arityrestriction of custom behaviors.Ryo Nakamura
-
Support
:url_safeoption forMessageEncryptor.The
MessageEncryptorconstructor now accepts a:url_safeoption, similar to theMessageVerifierconstructor. When enabled, this option ensures that messages use a URL-safe encoding.Jonathan Hefner
-
Add
url_safeoption toActiveSupport::MessageVerifierinitializerActiveSupport::MessageVerifier.newnow takes optionalurl_safeargument. It can generate URL-safe strings by passingurl_safe: true.verifier = ActiveSupport::MessageVerifier.new(url_safe: true) message = verifier.generate(data) # => URL-safe stringThis option is
falseby default to be backwards compatible.Shouichi Kamiya
-
Enable connection pooling by default for
MemCacheStoreandRedisCacheStore.If you want to disable connection pooling, set
:pooloption tofalsewhen configuring the cache store:config.cache_store = :mem_cache_store, "cache.example.com", pool: falsefatkodima
-
Add
force:support toActiveSupport::Cache::Store#fetch_multi.fatkodima
-
Deprecated
:pool_sizeand:pool_timeoutoptions for configuring connection pooling in cache stores.Use
pool: trueto enable pooling with default settings:config.cache_store = :redis_cache_store, pool: trueOr pass individual options via
:pooloption:config.cache_store = :redis_cache_store, pool: { size: 10, timeout: 2 }fatkodima
-
Allow #increment and #decrement methods of
ActiveSupport::Cache::Storesubclasses to set new values.Previously incrementing or decrementing an unset key would fail and return nil. A default will now be assumed and the key will be created.
Andrej Blagojević, Eugene Kenny
-
Add
skip_nil:support toRedisCacheStoreJoey Paris
-
ActiveSupport::Cache::MemoryStore#write(name, val, unless_exist:true)now correctly writes expired keys.Alan Savage
-
ActiveSupport::ErrorReporternow accepts and forward asource:parameter.This allow libraries to signal the origin of the errors, and reporters to easily ignore some sources.
Jean Boussier
-
Fix and add protections for XSS in
ActionView::HelpersandERB::Util.Add the method
ERB::Util.xml_name_escapeto escape dangerous characters in names of tags and names of attributes, following the specification of XML.Álvaro Martín Fraguas
-
Respect
ActiveSupport::Logger.new's:formatterkeyword argumentThe stdlib
Logger::newallows passing a:formatterkeyword argument to set the logger's formatter. PreviouslyActiveSupport::Logger.newignored that argument by always setting the formatter to an instance ofActiveSupport::Logger::SimpleFormatter.Steven Harman
-
Deprecate preserving the pre-Ruby 2.4 behavior of
to_timeWith Ruby 2.4+ the default for +to_time+ changed from converting to the local system time to preserving the offset of the receiver. At the time Rails supported older versions of Ruby so a compatibility layer was added to assist in the migration process. From Rails 5.0 new applications have defaulted to the Ruby 2.4+ behavior and since Rails 7.0 now only supports Ruby 2.7+ this compatibility layer can be safely removed.
To minimize any noise generated the deprecation warning only appears when the setting is configured to
falseas that is the only scenario where the removal of the compatibility layer has any effect.Andrew White
-
Pathname.blank?only returns true forPathname.new("")Previously it would end up calling
Pathname#empty?which returned true if the path existed and was an empty directory or file.That behavior was unlikely to be expected.
Jean Boussier
-
Deprecate
Notification::Event's#childrenand#parent_of?John Hawthorn
-
Change the default serializer of
ActiveSupport::MessageVerifierfromMarshaltoActiveSupport::JSONwhen usingconfig.load_defaults 7.1.Messages serialized with
Marshalcan still be read, but new messages will be serialized withActiveSupport::JSON. For more information, see https://guides.rubyonrails.org/v7.1/configuring.html#config-active-support-message-serializer.Saba Kiaei, David Buckley, and Jonathan Hefner
-
Change the default serializer of
ActiveSupport::MessageEncryptorfromMarshaltoActiveSupport::JSONwhen usingconfig.load_defaults 7.1.Messages serialized with
Marshalcan still be read, but new messages will be serialized withActiveSupport::JSON. For more information, see https://guides.rubyonrails.org/v7.1/configuring.html#config-active-support-message-serializer.Zack Deveau, Martin Gingras, and Jonathan Hefner
-
Add
ActiveSupport::TestCase#stub_constto stub a constant for the duration of a yield.DHH
-
Fix
ActiveSupport::EncryptedConfigurationto be compatible with Psych 4Stephen Sugden
-
Improve
File.atomic_writeerror handlingDaniel Pepper
-
Fix
Class#descendantsandDescendantsTracker#descendantscompatibility with Ruby 3.1.The native
Class#descendantswas reverted prior to Ruby 3.1 release, butClass#subclasseswas kept, breaking the feature detection.Jean Boussier
Active Model
-
Remove change in the typography of user facing error messages. For example, “can’t be blank” is again “can't be blank”.
Rafael Mendonça França
-
Support composite identifiers in
to_keyto_keyavoids wrapping#idvalue into anArrayif#idalready an arrayNikita Vasilevsky
-
Add
ActiveModel::Conversion.param_delimiterto configure delimiter being used into_paramNikita Vasilevsky
-
undefine_attribute_methodsundefines alias attribute methods along with attribute methods.Nikita Vasilevsky
-
Error.full_message now strips ":base" from the message.
zzak
-
Add a load hook for
ActiveModel::Model(namedactive_model) to match the load hook forActiveRecord::Baseand allow for overriding aspects of theActiveModel::Modelclass.Lewis Buckley
-
Improve password length validation in ActiveModel::SecurePassword to consider byte size for BCrypt compatibility.
The previous password length validation only considered the character count, which may not accurately reflect the 72-byte size limit imposed by BCrypt. This change updates the validation to consider both character count and byte size while keeping the character length validation in place.
user = User.new(password: "a" * 73) # 73 characters user.valid? # => false user.errors[:password] # => ["is too long"] user = User.new(password: "あ" * 25) # 25 characters, 75 bytes user.valid? # => false user.errors[:password] # => ["is too long"]ChatGPT, Guillermo Iguaran
-
has_secure_passwordnow generates an#{attribute}_saltmethod that returns the salt used to compute the password digest. The salt will change whenever the password is changed, so it can be used to create single-use password reset tokens withgenerates_token_for:class User < ActiveRecord::Base has_secure_password generates_token_for :password_reset, expires_in: 15.minutes do password_salt&.last(10) end endLázaro Nixon
-
Improve typography of user facing error messages. In English contractions, the Unicode APOSTROPHE (
U+0027) is now RIGHT SINGLE QUOTATION MARK (U+2019). For example, "can't be blank" is now "can’t be blank".Jon Dufresne
-
Add class to
ActiveModel::MissingAttributeErrorerror message.Show which class is missing the attribute in the error message:
user = User.first user.pets.select(:id).first.user_id # => ActiveModel::MissingAttributeError: missing attribute 'user_id' for PetPetrik de Heus
-
Raise
NoMethodErrorinActiveModel::Type::Value#as_jsonto avoid unpredictable results.Vasiliy Ermolovich
-
Custom attribute types that inherit from Active Model built-in types and do not override the
serializemethod will now benefit from an optimization when serializing attribute values for the database.For example, with a custom type like the following:
class DowncasedString < ActiveModel::Type::String def cast(value) super&.downcase end end ActiveRecord::Type.register(:downcased_string, DowncasedString) class User < ActiveRecord::Base attribute :email, :downcased_string end user = User.new(email: "FooBar@example.com")Serializing the
emailattribute for the database will be roughly twice as fast. More expensivecastoperations will likely see greater improvements.Jonathan Hefner
-
has_secure_passwordnow supports password challenges via apassword_challengeaccessor and validation.A password challenge is a safeguard to verify that the current user is actually the password owner. It can be used when changing sensitive model fields, such as the password itself. It is different than a password confirmation, which is used to prevent password typos.
When
password_challengeis set, the validation checks that the value's digest matches the currently persistedpassword_digest(i.e.password_digest_was).This allows a password challenge to be done as part of a typical
updatecall, just like a password confirmation. It also allows a password challenge error to be handled in the same way as other validation errors.For example, in the controller, instead of:
password_params = params.require(:password).permit( :password_challenge, :password, :password_confirmation, ) password_challenge = password_params.delete(:password_challenge) @password_challenge_failed = !current_user.authenticate(password_challenge) if !@password_challenge_failed && current_user.update(password_params) # ... endYou can now write:
password_params = params.require(:password).permit( :password_challenge, :password, :password_confirmation, ).with_defaults(password_challenge: "") if current_user.update(password_params) # ... endAnd, in the view, instead of checking
@password_challenge_failed, you can render an error for thepassword_challengefield just as you would for other form fields, including utilizingconfig.action_view.field_error_proc.Jonathan Hefner
-
Support infinite ranges for
LengthValidators:in/:withinoptionsvalidates_length_of :first_name, in: ..30fatkodima
-
Add support for beginless ranges to inclusivity/exclusivity validators:
validates_inclusion_of :birth_date, in: -> { (..Date.today) }validates_exclusion_of :birth_date, in: -> { (..Date.today) }Bo Jeanes
-
Make validators accept lambdas without record argument
# Before validates_comparison_of :birth_date, less_than_or_equal_to: ->(_record) { Date.today } # After validates_comparison_of :birth_date, less_than_or_equal_to: -> { Date.today }fatkodima
-
Fix casting long strings to
Date,TimeorDateTimefatkodima
-
Use different cache namespace for proxy calls
Models can currently have different attribute bodies for the same method names, leading to conflicts. Adding a new namespace
:active_model_proxyfixes the issue.Chris Salzberg
Active Record
-
Remove -shm and -wal SQLite files when
rails db:dropis run.Niklas Häusele
-
Revert the change to raise an
ArgumentErrorwhen#accepts_nested_attributes_foris declared more than once for an association in the same class.The reverted behavior broke the case where the
#accepts_nested_attributes_forwas defined in a concern and where overridden in the class that included the concern.Rafael Mendonça França
-
Better naming for unique constraints support.
Naming unique keys leads to misunderstanding it's a short-hand of unique indexes. Just naming it unique constraints is not misleading.
In Rails 7.1.0.beta1 or before:
add_unique_key :sections, [:position], deferrable: :deferred, name: "unique_section_position" remove_unique_key :sections, name: "unique_section_position"Now:
add_unique_constraint :sections, [:position], deferrable: :deferred, name: "unique_section_position" remove_unique_constraint :sections, name: "unique_section_position"Ryuta Kamizono
-
Fix duplicate quoting for check constraint expressions in schema dump when using MySQL
A check constraint with an expression, that already contains quotes, lead to an invalid schema dump with the mysql2 adapter.
Fixes #42424.
Felix Tscheulin
-
Performance tune the SQLite3 adapter connection configuration
For Rails applications, the Write-Ahead-Log in normal syncing mode with a capped journal size, a healthy shared memory buffer and a shared cache will perform, on average, 2× better.
Stephen Margheim
-
Allow SQLite3
busy_handlerto be configured with simple max number ofretriesRetrying busy connections without delay is a preferred practice for performance-sensitive applications. Add support for a
database.ymlretriesinteger, which is used in a simplebusy_handlerfunction to retry busy connections without exponential backoff up to the max number ofretries.Stephen Margheim
-
The SQLite3 adapter now supports
supports_insert_returning?Implementing the full
supports_insert_returning?contract means the SQLite3 adapter supports auto-populated columns (#48241) as well as custom primary keys.Stephen Margheim
-
Ensure the SQLite3 adapter handles default functions with the
||concatenation operatorPreviously, this default function would produce the static string
"'Ruby ' || 'on ' || 'Rails'". Now, the adapter will appropriately receive and use"Ruby on Rails".change_column_default "test_models", "ruby_on_rails", -> { "('Ruby ' || 'on ' || 'Rails')" }Stephen Margheim
-
Dump PostgreSQL schemas as part of the schema dump.
Lachlan Sylvester
-
Encryption now supports
support_unencrypted_databeing set per-attribute.You can now opt out of
support_unencrypted_dataon a specific encrypted attribute. This only has an effect ifActiveRecord::Encryption.config.support_unencrypted_data == true.class User < ActiveRecord::Base encrypts :name, deterministic: true, support_unencrypted_data: false encrypts :email, deterministic: true endAlex Ghiculescu
-
Add instrumentation for Active Record transactions
Allows subscribing to transaction events for tracking/instrumentation. The event payload contains the connection and the outcome (commit, rollback, restart, incomplete), as well as timing details.
ActiveSupport::Notifications.subscribe("transaction.active_record") do |event| puts "Transaction event occurred!" connection = event.payload[:connection] puts "Connection: #{connection.inspect}" endDaniel Colson, Ian Candy
-
Support composite foreign keys via migration helpers.
# Assuming "carts" table has "(shop_id, user_id)" as a primary key. add_foreign_key(:orders, :carts, primary_key: [:shop_id, :user_id]) remove_foreign_key(:orders, :carts, primary_key: [:shop_id, :user_id]) foreign_key_exists?(:orders, :carts, primary_key: [:shop_id, :user_id])fatkodima
-
Adds support for
if_not_existswhen adding a check constraint.add_check_constraint :posts, "post_type IN ('blog', 'comment', 'share')", if_not_exists: trueCody Cutrer
-
Raise an
ArgumentErrorwhen#accepts_nested_attributes_foris declared more than once for an association in the same class. Previously, the last declaration would silently override the previous one. Overriding in a subclass is still allowed.Joshua Young
-
Deprecate
rewhereargument on#merge.The
rewhereargument on#mergeis deprecated without replacement and will be removed in Rails 7.2.Adam Hess
-
Fix unscope is not working in specific case
Before:
Post.where(id: 1...3).unscope(where: :id).to_sql # "SELECT `posts`.* FROM `posts` WHERE `posts`.`id` >= 1 AND `posts`.`id` < 3"After:
Post.where(id: 1...3).unscope(where: :id).to_sql # "SELECT `posts`.* FROM `posts`"Fixes #48094.
Kazuya Hatanaka
-
Change
has_secure_tokendefault toon: :initializeChange the new default value from
on: :createtoon: :initializeCan be controlled by the
config.active_record.generate_secure_token_onconfiguration:config.active_record.generate_secure_token_on = :createSean Doyle
-
Fix
change_columnnot settingprecision: 6ondatetimecolumns when using 7.0+ Migrations and SQLite.Hartley McGuire
-
Support composite identifiers in
to_keyto_keyavoids wrapping#idvalue into anArrayif#idalready an arrayNikita Vasilevsky
-
Add validation option for
enumclass Contract < ApplicationRecord enum :status, %w[in_progress completed], validate: true end Contract.new(status: "unknown").valid? # => false Contract.new(status: nil).valid? # => false Contract.new(status: "completed").valid? # => true class Contract < ApplicationRecord enum :status, %w[in_progress completed], validate: { allow_nil: true } end Contract.new(status: "unknown").valid? # => false Contract.new(status: nil).valid? # => true Contract.new(status: "completed").valid? # => trueEdem Topuzov, Ryuta Kamizono
-
Allow batching methods to use already loaded relation if available
Calling batch methods on already loaded relations will use the records previously loaded instead of retrieving them from the database again.
Adam Hess
-
Deprecate
read_attribute(:id)returning the primary key if the primary key is not:id.Starting in Rails 7.2,
read_attribute(:id)will return the value of the id column, regardless of the model's primary key. To retrieve the value of the primary key, use#idinstead.read_attribute(:id)for composite primary key models will now return the value of the id column.Adrianna Chang
-
Fix
change_tablesetting datetime precision for 6.1 MigrationsHartley McGuire
-
Fix change_column setting datetime precision for 6.1 Migrations
Hartley McGuire
-
Add
ActiveRecord::Base#id_valuealias to access the raw value of a record's id column.This alias is only provided for models that declare an
:idcolumn.Adrianna Chang
-
Fix previous change tracking for
ActiveRecord::Storewhen using a column with JSON structured database typeBefore, the methods to access the changes made during the last save
#saved_change_to_key?,#saved_change_to_key, and#key_before_last_savedid not work if the store was defined as astore_accessoron a column with a JSON structured database typeRobert DiMartino
-
Fully support
NULLS [NOT] DISTINCTfor PostgreSQL 15+ indexes.Previous work was done to allow the index to be created in a migration, but it was not supported in schema.rb. Additionally, the matching for
NULLS [NOT] DISTINCTwas not in the correct order, which could have resulted in inconsistent schema detection.Gregory Jones
-
Allow escaping of literal colon characters in
sanitize_sql_*methods when named bind variables are usedJustin Bull
-
Fix
#previously_new_record?to return true for destroyed records.Before, if a record was created and then destroyed,
#previously_new_record?would return true. Now, any UPDATE or DELETE to a record is considered a change, and will result in#previously_new_record?returning false.Adrianna Chang
-
Specify callback in
has_secure_tokenclass User < ApplicationRecord has_secure_token on: :initialize end User.new.token # => "abc123...."Sean Doyle
-
Fix incrementation of in memory counter caches when associations overlap
When two associations had a similarly named counter cache column, Active Record could sometime increment the wrong one.
Jacopo Beschi, Jean Boussier
-
Don't show secrets for Active Record's
Cipher::Aes256Gcm#inspect.Before:
ActiveRecord::Encryption::Cipher::Aes256Gcm.new(secret).inspect "#<ActiveRecord::Encryption::Cipher::Aes256Gcm:0x0000000104888038 ... @secret=\"\\xAF\\bFh]LV}q\\nl\\xB2U\\xB3 ... >"After:
ActiveRecord::Encryption::Cipher::Aes256Gcm(secret).inspect "#<ActiveRecord::Encryption::Cipher::Aes256Gcm:0x0000000104888038>"Petrik de Heus
-
Bring back the historical behavior of committing transaction on non-local return.
Model.transaction do model.save return other_model.save # not executed endHistorically only raised errors would trigger a rollback, but in Ruby
2.3, thetimeoutlibrary started usingthrowto interrupt execution which had the adverse effect of committing open transactions.To solve this, in Active Record 6.1 the behavior was changed to instead rollback the transaction as it was safer than to potentially commit an incomplete transaction.
Using
return,breakorthrowinside atransactionblock was essentially deprecated from Rails 6.1 onwards.However with the release of
timeout 0.4.0,Timeout.timeoutnow raises an error again, and Active Record is able to return to its original, less surprising, behavior.This historical behavior can now be opt-ed in via:
Rails.application.config.active_record.commit_transaction_on_non_local_return = trueAnd is the default for new applications created in Rails 7.1.
Jean Boussier
-
Deprecate
nameargument on#remove_connection.The
nameargument is deprecated on#remove_connectionwithout replacement.#remove_connectionshould be called directly on the class that established the connection.Eileen M. Uchitelle
-
Fix has_one through singular building with inverse.
Allows building of records from an association with a has_one through a singular association with inverse. For belongs_to through associations, linking the foreign key to the primary key model isn't needed. For has_one, we cannot build records due to the association not being mutable.
Gannon McGibbon
-
Disable database prepared statements when query logs are enabled
Prepared Statements and Query Logs are incompatible features due to query logs making every query unique.
zzak, Jean Boussier
-
Support decrypting data encrypted non-deterministically with a SHA1 hash digest.
This adds a new Active Record encryption option to support decrypting data encrypted non-deterministically with a SHA1 hash digest:
Rails.application.config.active_record.encryption.support_sha1_for_non_deterministic_encryption = trueThe new option addresses a problem when upgrading from 7.0 to 7.1. Due to a bug in how Active Record Encryption was getting initialized, the key provider used for non-deterministic encryption were using SHA-1 as its digest class, instead of the one configured globally by Rails via
Rails.application.config.active_support.key_generator_hash_digest_class.Cadu Ribeiro and Jorge Manrubia
-
Added PostgreSQL migration commands for enum rename, add value, and rename value.
rename_enumandrename_enum_valueare reversible. Due to Postgres limitation,add_enum_valueis not reversible since you cannot delete enum values. As an alternative you should drop and recreate the enum entirely.rename_enum :article_status, to: :article_stateadd_enum_value :article_state, "archived" # will be at the end of existing values add_enum_value :article_state, "in review", before: "published" add_enum_value :article_state, "approved", after: "in review"rename_enum_value :article_state, from: "archived", to: "deleted"Ray Faddis
-
Allow composite primary key to be derived from schema
Booting an application with a schema that contains composite primary keys will not issue warning and won't
nilify theActiveRecord::Base#primary_keyvalue anymore.Given a
travel_routestable definition and aTravelRoutemodel like:create_table :travel_routes, primary_key: [:origin, :destination], force: true do |t| t.string :origin t.string :destination end class TravelRoute < ActiveRecord::Base; endThe
TravelRoute.primary_keyvalue will be automatically derived to["origin", "destination"]Nikita Vasilevsky
-
Include the
connection_poolwith exceptions raised from an adapter.The
connection_poolprovides added context such as the connection used that led to the exception as well as which role and shard.Luan Vieira
-
Support multiple column ordering for
find_each,find_in_batchesandin_batches.When find_each/find_in_batches/in_batches are performed on a table with composite primary keys, ascending or descending order can be selected for each key.
Person.find_each(order: [:desc, :asc]) do |person| person.party_all_night! endTakuya Kurimoto
-
Fix where on association with has_one/has_many polymorphic relations.
Before:
Treasure.where(price_estimates: PriceEstimate.all) #=> SELECT (...) WHERE "treasures"."id" IN (SELECT "price_estimates"."estimate_of_id" FROM "price_estimates")Later:
Treasure.where(price_estimates: PriceEstimate.all) #=> SELECT (...) WHERE "treasures"."id" IN (SELECT "price_estimates"."estimate_of_id" FROM "price_estimates" WHERE "price_estimates"."estimate_of_type" = 'Treasure')Lázaro Nixon
-
Assign auto populated columns on Active Record record creation.
Changes record creation logic to allow for the
auto_incrementcolumn to be assigned immediately after creation regardless of it's relation to the model's primary key.The PostgreSQL adapter benefits the most from the change allowing for any number of auto-populated columns to be assigned on the object immediately after row insertion utilizing the
RETURNINGstatement.Nikita Vasilevsky
-
Use the first key in the
shardshash fromconnected_tofor thedefault_shard.Some applications may not want to use
:defaultas a shard name in their connection model. Unfortunately Active Record expects there to be a:defaultshard because it must assume a shard to get the right connection from the pool manager. Rather than force applications to manually set this,connects_tocan infer the default shard name from the hash of shards and will now assume that the first shard is your default.For example if your model looked like this:
class ShardRecord < ApplicationRecord self.abstract_class = true connects_to shards: { shard_one: { writing: :shard_one }, shard_two: { writing: :shard_two } }Then the
default_shardfor this class would be set toshard_one.Fixes: #45390
Eileen M. Uchitelle
-
Fix mutation detection for serialized attributes backed by binary columns.
Jean Boussier
-
Add
ActiveRecord.disconnect_all!method to immediately close all connections from all pools.Jean Boussier
-
Discard connections which may have been left in a transaction.
There are cases where, due to an error,
within_new_transactionmay unexpectedly leave a connection in an open transaction. In these cases the connection may be reused, and the following may occur:- Writes appear to fail when they actually succeed.
- Writes appear to succeed when they actually fail.
- Reads return stale or uncommitted data.
Previously, the following case was detected:
- An error is encountered during the transaction, then another error is encountered while attempting to roll it back.
Now, the following additional cases are detected:
- An error is encountered just after successfully beginning a transaction.
- An error is encountered while committing a transaction, then another error is encountered while attempting to roll it back.
- An error is encountered while rolling back a transaction.
Nick Dower
-
Active Record query cache now evicts least recently used entries
By default it only keeps the
100most recently used queries.The cache size can be configured via
database.ymldevelopment: adapter: mysql2 query_cache: 200It can also be entirely disabled:
development: adapter: mysql2 query_cache: falseJean Boussier
-
Deprecate
check_pending!in favor ofcheck_all_pending!.check_pending!will only check for pending migrations on the current database connection or the one passed in. This has been deprecated in favor ofcheck_all_pending!which will find all pending migrations for the database configurations in a given environment.Eileen M. Uchitelle
-
Make
increment_counter/decrement_counteraccept an amount argumentPost.increment_counter(:comments_count, 5, by: 3)fatkodima
-
Add support for
Array#intersect?toActiveRecord::Relation.Array#intersect?is only available on Ruby 3.1 or later.This allows the Rubocop
Style/ArrayIntersectcop to work withActiveRecord::Relationobjects.John Harry Kelly
-
The deferrable foreign key can be passed to
t.references.Hiroyuki Ishii
-
Deprecate
deferrable: trueoption ofadd_foreign_key.deferrable: trueis deprecated in favor ofdeferrable: :immediate, and will be removed in Rails 7.2.Because
deferrable: trueanddeferrable: :deferredare hard to understand. Both true and :deferred are truthy values. This behavior is the same as the deferrable option of the add_unique_key method, added in #46192.Hiroyuki Ishii
-
AbstractAdapter#executeand#exec_querynow clear the query cacheIf you need to perform a read only SQL query without clearing the query cache, use
AbstractAdapter#select_all.Jean Boussier
-
Make
.joins/.left_outer_joinswork with CTEs.For example:
Post .with(commented_posts: Comment.select(:post_id).distinct) .joins(:commented_posts) #=> WITH (...) SELECT ... INNER JOIN commented_posts on posts.id = commented_posts.post_idVladimir Dementyev
-
Add a load hook for
ActiveRecord::ConnectionAdapters::Mysql2Adapter(namedactive_record_mysql2adapter) to allow for overriding aspects of theActiveRecord::ConnectionAdapters::Mysql2Adapterclass. This makesMysql2Adapterconsistent withPostgreSQLAdapterandSQLite3Adapterthat already have load hooks.fatkodima
-
Introduce adapter for Trilogy database client
Trilogy is a MySQL-compatible database client. Rails applications can use Trilogy by configuring their
config/database.yml:development: adapter: trilogy database: blog_development pool: 5Or by using the
DATABASE_URLenvironment variable:ENV['DATABASE_URL'] # => "trilogy://localhost/blog_development?pool=5"Adrianna Chang
-
after_commitcallbacks defined on models now execute in the correct order.class User < ActiveRecord::Base after_commit { puts("this gets called first") } after_commit { puts("this gets called second") } endPreviously, the callbacks executed in the reverse order. To opt in to the new behaviour:
config.active_record.run_after_transaction_callbacks_in_order_defined = trueThis is the default for new apps.
Alex Ghiculescu
-
Infer
foreign_keywheninverse_ofis present onhas_oneandhas_manyassociations.has_many :citations, foreign_key: "book1_id", inverse_of: :bookcan be simplified to
has_many :citations, inverse_of: :bookand the foreign_key will be read from the corresponding
belongs_toassociation.Daniel Whitney
-
Limit max length of auto generated index names
Auto generated index names are now limited to 62 bytes, which fits within the default index name length limits for MySQL, Postgres and SQLite.
Any index name over the limit will fallback to the new short format.
Before (too long):
index_testings_on_foo_and_bar_and_first_name_and_last_name_and_administratorAfter (short format):
idx_on_foo_bar_first_name_last_name_administrator_5939248142The short format includes a hash to ensure the name is unique database-wide.
Mike Coutermarsh
-
Introduce a more stable and optimized Marshal serializer for Active Record models.
Can be enabled with
config.active_record.marshalling_format_version = 7.1.Jean Boussier
-
Allow specifying where clauses with column-tuple syntax.
Querying through
#wherenow accepts a new tuple-syntax which accepts, as a key, an array of columns and, as a value, an array of corresponding tuples. The key specifies a list of columns, while the value is an array of ordered-tuples that conform to the column list.For instance:
# Cpk::Book => Cpk::Book(author_id: integer, number: integer, title: string, revision: integer) # Cpk::Book.primary_key => ["author_id", "number"] book = Cpk::Book.create!(author_id: 1, number: 1) Cpk::Book.where(Cpk::Book.primary_key => [[1, 2]]) # => [book] # Topic => Topic(id: integer, title: string, author_name: string...) Topic.where([:title, :author_name] => [["The Alchemist", "Paulo Coelho"], ["Harry Potter", "J.K Rowling"]])Paarth Madan
-
Allow warning codes to be ignore when reporting SQL warnings.
Active Record config that can ignore warning codes
# Configure allowlist of warnings that should always be ignored config.active_record.db_warnings_ignore = [ "1062", # MySQL Error 1062: Duplicate entry ]This is supported for the MySQL and PostgreSQL adapters.
Nick Borromeo
-
Introduce
:active_record_fixtureslazy load hook.Hooks defined with this name will be run whenever
TestFixturesis included in a class.ActiveSupport.on_load(:active_record_fixtures) do self.fixture_paths << "test/fixtures" end klass = Class.new klass.include(ActiveRecord::TestFixtures) klass.fixture_paths # => ["test/fixtures"]Andrew Novoselac
-
Introduce
TestFixtures#fixture_paths.Multiple fixture paths can now be specified using the
#fixture_pathsaccessor. Apps will continue to havetest/fixturesas their one fixture path by default, but additional fixture paths can be specified.ActiveSupport::TestCase.fixture_paths << "component1/test/fixtures" ActiveSupport::TestCase.fixture_paths << "component2/test/fixtures"TestFixtures#fixture_pathis now deprecated.Andrew Novoselac
-
Adds support for deferrable exclude constraints in PostgreSQL.
By default, exclude constraints in PostgreSQL are checked after each statement. This works for most use cases, but becomes a major limitation when replacing records with overlapping ranges by using multiple statements.
exclusion_constraint :users, "daterange(valid_from, valid_to) WITH &&", deferrable: :immediatePassing
deferrable: :immediatechecks constraint after each statement, but allows manually deferring the check usingSET CONSTRAINTS ALL DEFERREDwithin a transaction. This will cause the excludes to be checked after the transaction.It's also possible to change the default behavior from an immediate check (after the statement), to a deferred check (after the transaction):
exclusion_constraint :users, "daterange(valid_from, valid_to) WITH &&", deferrable: :deferredHiroyuki Ishii
-
Respect
foreign_typeoption todelegated_typefor{role}_classmethod.Usage of
delegated_typewith non-conventional{role}_typecolumn names can now be specified withforeign_typeoption. This option is the same asforeign_typeas forwarded to the underlyingbelongs_toassociation thatdelegated_typewraps.Jason Karns
-
Add support for unique constraints (PostgreSQL-only).
add_unique_key :sections, [:position], deferrable: :deferred, name: "unique_section_position" remove_unique_key :sections, name: "unique_section_position"See PostgreSQL's Unique Constraints documentation for more on unique constraints.
By default, unique constraints in PostgreSQL are checked after each statement. This works for most use cases, but becomes a major limitation when replacing records with unique column by using multiple statements.
An example of swapping unique columns between records.
# position is unique column old_item = Item.create!(position: 1) new_item = Item.create!(position: 2) Item.transaction do old_item.update!(position: 2) new_item.update!(position: 1) endUsing the default behavior, the transaction would fail when executing the first
UPDATEstatement.By passing the
:deferrableoption to theadd_unique_keystatement in migrations, it's possible to defer this check.add_unique_key :items, [:position], deferrable: :immediatePassing
deferrable: :immediatedoes not change the behaviour of the previous example, but allows manually deferring the check usingSET CONSTRAINTS ALL DEFERREDwithin a transaction. This will cause the unique constraints to be checked after the transaction.It's also possible to adjust the default behavior from an immediate check (after the statement), to a deferred check (after the transaction):
add_unique_key :items, [:position], deferrable: :deferredIf you want to change an existing unique index to deferrable, you can use :using_index to create deferrable unique constraints.
add_unique_key :items, deferrable: :deferred, using_index: "index_items_on_position"Hiroyuki Ishii
-
Remove deprecated
Tasks::DatabaseTasks.schema_file_type.Rafael Mendonça França
-
Remove deprecated
config.active_record.partial_writes.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Baseconfig accessors.Rafael Mendonça França
-
Remove the
:include_replicasargument fromconfigs_for. Use:include_hiddenargument instead.Eileen M. Uchitelle
-
Allow applications to lookup a config via a custom hash key.
If you have registered a custom config or want to find configs where the hash matches a specific key, now you can pass
config_keytoconfigs_for. For example if you have adb_configwith the keyvitessyou can look up a database configuration hash by matching that key.ActiveRecord::Base.configurations.configs_for(env_name: "development", name: "primary", config_key: :vitess) ActiveRecord::Base.configurations.configs_for(env_name: "development", config_key: :vitess)Eileen M. Uchitelle
-
Allow applications to register a custom database configuration handler.
Adds a mechanism for registering a custom handler for cases where you want database configurations to respond to custom methods. This is useful for non-Rails database adapters or tools like Vitess that you may want to configure differently from a standard
HashConfigorUrlConfig.Given the following database YAML we want the
animalsdb to create aCustomConfigobject instead while theprimarydatabase will be aUrlConfig:development: primary: url: postgres://localhost/primary animals: url: postgres://localhost/animals custom_config: sharded: 1To register a custom handler first make a class that has your custom methods:
class CustomConfig < ActiveRecord::DatabaseConfigurations::UrlConfig def sharded? custom_config.fetch("sharded", false) end private def custom_config configuration_hash.fetch(:custom_config) end endThen register the config in an initializer:
ActiveRecord::DatabaseConfigurations.register_db_config_handler do |env_name, name, url, config| next unless config.key?(:custom_config) CustomConfig.new(env_name, name, url, config) endWhen the application is booted, configuration hashes with the
:custom_configkey will beCustomConfigobjects and respond tosharded?. Applications must handle the condition in which Active Record should use their custom handler.Eileen M. Uchitelle and John Crepezzi
-
ActiveRecord::Base.serializeno longer uses YAML by default.YAML isn't particularly performant and can lead to security issues if not used carefully.
Unfortunately there isn't really any good serializers in Ruby's stdlib to replace it.
The obvious choice would be JSON, which is a fine format for this use case, however the JSON serializer in Ruby's stdlib isn't strict enough, as it fallback to casting unknown types to strings, which could lead to corrupted data.
Some third party JSON libraries like
Ojhave a suitable strict mode.So it's preferable that users choose a serializer based on their own constraints.
The original default can be restored by setting
config.active_record.default_column_serializer = YAML.Jean Boussier
-
ActiveRecord::Base.serializesignature changed.Rather than a single positional argument that accepts two possible types of values,
serializenow accepts two distinct keyword arguments.Before:
serialize :content, JSON serialize :backtrace, ArrayAfter:
serialize :content, coder: JSON serialize :backtrace, type: ArrayJean Boussier
-
YAML columns use
YAML.safe_dumpif available.As of
psych 5.1.0,YAML.safe_dumpcan now apply the same permitted types restrictions thanYAML.safe_load.It's preferable to ensure the payload only use allowed types when we first try to serialize it, otherwise you may end up with invalid records in the database.
Jean Boussier
-
ActiveRecord::QueryLogsbetter handle broken encoding.It's not uncommon when building queries with BLOB fields to contain binary data. Unless the call carefully encode the string in ASCII-8BIT it generally end up being encoded in
UTF-8, andQueryLogswould end up failing on it.ActiveRecord::QueryLogsno longer depend on the query to be properly encoded.Jean Boussier
-
Fix a bug where
ActiveRecord::Generators::ModelGeneratorwould not respect create_table_migration template overrides.rails g model create_books title:string content:textwill now read from the create_table_migration.rb.tt template in the following locations in order:
lib/templates/active_record/model/create_table_migration.rb lib/templates/active_record/migration/create_table_migration.rbSpencer Neste
-
ActiveRecord::Relation#explainnow accepts options.For databases and adapters which support them (currently PostgreSQL and MySQL), options can be passed to
explainto provide more detailed query plan analysis:Customer.where(id: 1).joins(:orders).explain(:analyze, :verbose)Reid Lynch
-
Multiple
Arel::Nodes::SqlLiteralnodes can now be added together to formArel::Nodes::Fragmentsnodes. This allows joining several pieces of SQL.Matthew Draper, Ole Friis
-
ActiveRecord::Base#signed_idraises if called on a new record.Previously it would return an ID that was not usable, since it was based on
id = nil.Alex Ghiculescu
-
Allow SQL warnings to be reported.
Active Record configs can be set to enable SQL warning reporting.
# Configure action to take when SQL query produces warning config.active_record.db_warnings_action = :raise # Configure allowlist of warnings that should always be ignored config.active_record.db_warnings_ignore = [ /Invalid utf8mb4 character string/, "An exact warning message", ]This is supported for the MySQL and PostgreSQL adapters.
Adrianna Chang, Paarth Madan
-
Add
#regroupquery method as a short-hand for.unscope(:group).group(fields)Example:
Post.group(:title).regroup(:author) # SELECT `posts`.`*` FROM `posts` GROUP BY `posts`.`author`Danielius Visockas
-
PostgreSQL adapter method
enable_extensionnow allows parameter to be[schema_name.]<extension_name>if the extension must be installed on another schema.Example:
enable_extension('heroku_ext.hstore')Leonardo Luarte
-
Add
:includeoption toadd_index.Add support for including non-key columns in indexes for PostgreSQL with the
INCLUDEparameter.add_index(:users, :email, include: [:id, :created_at])will result in:
CREATE INDEX index_users_on_email USING btree (email) INCLUDE (id, created_at)Steve Abrams
-
ActiveRecord::Relation’s#any?,#none?, and#one?methods take an optional pattern argument, more closely matching theirEnumerableequivalents.George Claghorn
-
Add
ActiveRecord::Base.normalizesfor declaring attribute normalizations.An attribute normalization is applied when the attribute is assigned or updated, and the normalized value will be persisted to the database. The normalization is also applied to the corresponding keyword argument of query methods, allowing records to be queried using unnormalized values.
For example:
class User < ActiveRecord::Base normalizes :email, with: -> email { email.strip.downcase } normalizes :phone, with: -> phone { phone.delete("^0-9").delete_prefix("1") } end user = User.create(email: " CRUISE-CONTROL@EXAMPLE.COM\n") user.email # => "cruise-control@example.com" user = User.find_by(email: "\tCRUISE-CONTROL@EXAMPLE.COM ") user.email # => "cruise-control@example.com" user.email_before_type_cast # => "cruise-control@example.com" User.where(email: "\tCRUISE-CONTROL@EXAMPLE.COM ").count # => 1 User.where(["email = ?", "\tCRUISE-CONTROL@EXAMPLE.COM "]).count # => 0 User.exists?(email: "\tCRUISE-CONTROL@EXAMPLE.COM ") # => true User.exists?(["email = ?", "\tCRUISE-CONTROL@EXAMPLE.COM "]) # => false User.normalize_value_for(:phone, "+1 (555) 867-5309") # => "5558675309"Jonathan Hefner
-
Hide changes to before_committed! callback behaviour behind flag.
In #46525, behavior around before_committed! callbacks was changed so that callbacks would run on every enrolled record in a transaction, not just the first copy of a record. This change in behavior is now controlled by a configuration option,
config.active_record.before_committed_on_all_records. It will be enabled by default on Rails 7.1.Adrianna Chang
-
The
namespaced_controllerQuery Log tag now matches thecontrollerformatFor example, a request processed by
NameSpaced::UsersControllerwill now log as::controller # "users" :namespaced_controller # "name_spaced/users"Alex Ghiculescu
-
Return only unique ids from ActiveRecord::Calculations#ids
Updated ActiveRecord::Calculations#ids to only return the unique ids of the base model when using eager_load, preload and includes.
Post.find_by(id: 1).comments.count # => 5 Post.includes(:comments).where(id: 1).pluck(:id) # => [1, 1, 1, 1, 1] Post.includes(:comments).where(id: 1).ids # => [1]Joshua Young
-
Stop using
LOWER()for case-insensitive queries oncitextcolumnsPreviously,
LOWER()was added for e.g. uniqueness validations withcase_sensitive: false. It wasn't mentioned in the documentation that the index withoutLOWER()wouldn't be used in this case.Phil Pirozhkov
-
Extract
#sync_timezone_changesmethod in AbstractMysqlAdapter to enable subclasses to sync database timezone changes without overriding#raw_execute.Adrianna Chang, Paarth Madan
-
Do not write additional new lines when dumping sql migration versions
This change updates the
insert_versions_sqlfunction so that the database insert string containing the current database migration versions does not end with two additional new lines.Misha Schwartz
-
Fix
composed_ofvalue freezing and duplication.Previously composite values exhibited two confusing behaviors:
- When reading a compositve value it'd NOT be frozen, allowing it to get out of sync with its underlying database columns.
- When writing a compositve value the argument would be frozen, potentially confusing the caller.
Currently, composite values instantiated based on database columns are frozen (addressing the first issue) and assigned compositve values are duplicated and the duplicate is frozen (addressing the second issue).
Greg Navis
-
Fix redundant updates to the column insensitivity cache
Fixed redundant queries checking column capability for insensitive comparison.
Phil Pirozhkov
-
Allow disabling methods generated by
ActiveRecord.enum.Alfred Dominic
-
Avoid validating
belongs_toassociation if it has not changed.Previously, when updating a record, Active Record will perform an extra query to check for the presence of
belongs_toassociations (if the presence is configured to be mandatory), even if that attribute hasn't changed.Currently, only
belongs_to-related columns are checked for presence. It is possible to have orphaned records with this approach. To avoid this problem, you need to use a foreign key.This behavior can be controlled by configuration:
config.active_record.belongs_to_required_validates_foreign_key = falseand will be disabled by default with
config.load_defaults 7.1.fatkodima
-
has_oneandbelongs_toassociations now define areset_associationmethod on the owner model (whereassociationis the name of the association). This method unloads the cached associate record, if any, and causes the next access to query it from the database.George Claghorn
-
Allow per attribute setting of YAML permitted classes (safe load) and unsafe load.
Carlos Palhares
-
Add a build persistence method
Provides a wrapper for
new, to provide feature parity withcreates ability to create multiple records from an array of hashes, using the same notation as thebuildmethod on associations.Sean Denny
-
Raise on assignment to readonly attributes
class Post < ActiveRecord::Base attr_readonly :content end Post.create!(content: "cannot be updated") post.content # "cannot be updated" post.content = "something else" # => ActiveRecord::ReadonlyAttributeErrorPreviously, assignment would succeed but silently not write to the database.
This behavior can be controlled by configuration:
config.active_record.raise_on_assign_to_attr_readonly = trueand will be enabled by default with
config.load_defaults 7.1.Alex Ghiculescu, Hartley McGuire
-
Allow unscoping of preload and eager_load associations
Added the ability to unscope preload and eager_load associations just like includes, joins, etc. See ActiveRecord::QueryMethods::VALID_UNSCOPING_VALUES for the full list of supported unscopable scopes.
query.unscope(:eager_load, :preload).group(:id).select(:id)David Morehouse
-
Add automatic filtering of encrypted attributes on inspect
This feature is enabled by default but can be disabled with
config.active_record.encryption.add_to_filter_parameters = falseHartley McGuire
-
Clear locking column on #dup
This change fixes not to duplicate locking_column like id and timestamps.
car = Car.create! car.touch car.lock_version #=> 1 car.dup.lock_version #=> 0Shouichi Kamiya, Seonggi Yang, Ryohei UEDA
-
Invalidate transaction as early as possible
After rescuing a
TransactionRollbackErrorexception Rails invalidates transactions earlier in the flow allowing the framework to skip issuing theROLLBACKstatement in more cases. Only affects adapters that havesavepoint_errors_invalidate_transactions?configured astrue, which at this point is only applicable to themysql2adapter.Nikita Vasilevsky
-
Allow configuring columns list to be used in SQL queries issued by an
ActiveRecord::BaseobjectIt is now possible to configure columns list that will be used to build an SQL query clauses when updating, deleting or reloading an
ActiveRecord::Baseobjectclass Developer < ActiveRecord::Base query_constraints :company_id, :id end developer = Developer.first.update(name: "Bob") # => UPDATE "developers" SET "name" = 'Bob' WHERE "developers"."company_id" = 1 AND "developers"."id" = 1Nikita Vasilevsky
-
Adds
validateto foreign keys and check constraints in schema.rbPreviously,
schema.rbwould not record ifvalidate: falsehad been used when adding a foreign key or check constraint, so restoring a database from the schema could result in foreign keys or check constraints being incorrectly validated.Tommy Graves
-
Adapter
#executemethods now accept anallow_retryoption. When set totrue, the SQL statement will be retried, up to the database's configuredconnection_retriesvalue, upon encountering connection-related errors.Adrianna Chang
-
Only trigger
after_commit :destroycallbacks when a database row is deleted.This prevents
after_commit :destroycallbacks from being triggered again whendestroyis called multiple times on the same record.Ben Sheldon
-
Fix
ciphertext_forfor yet-to-be-encrypted values.Previously,
ciphertext_forreturned the cleartext of values that had not yet been encrypted, such as with an unpersisted record:Post.encrypts :body post = Post.create!(body: "Hello") post.ciphertext_for(:body) # => "{\"p\":\"abc..." post.body = "World" post.ciphertext_for(:body) # => "World"Now,
ciphertext_forwill always return the ciphertext of encrypted attributes:Post.encrypts :body post = Post.create!(body: "Hello") post.ciphertext_for(:body) # => "{\"p\":\"abc..." post.body = "World" post.ciphertext_for(:body) # => "{\"p\":\"xyz..."Jonathan Hefner
-
Fix a bug where using groups and counts with long table names would return incorrect results.
Shota Toguchi, Yusaku Ono
-
Fix encryption of column default values.
Previously, encrypted attributes that used column default values appeared to be encrypted on create, but were not:
Book.encrypts :name book = Book.create! book.name # => "<untitled>" book.name_before_type_cast # => "{\"p\":\"abc..." book.reload.name_before_type_cast # => "<untitled>"Now, attributes with column default values are encrypted:
Book.encrypts :name book = Book.create! book.name # => "<untitled>" book.name_before_type_cast # => "{\"p\":\"abc..." book.reload.name_before_type_cast # => "{\"p\":\"abc..."Jonathan Hefner
-
Deprecate delegation from
Basetoconnection_handler.Calling
Base.clear_all_connections!,Base.clear_active_connections!,Base.clear_reloadable_connections!andBase.flush_idle_connections!is deprecated. Please call these methods on the connection handler directly. In future Rails versions, the delegation fromBaseto theconnection_handlerwill be removed.Eileen M. Uchitelle
-
Allow ActiveRecord::QueryMethods#reselect to receive hash values, similar to ActiveRecord::QueryMethods#select
Sampat Badhe
-
Validate options when managing columns and tables in migrations.
If an invalid option is passed to a migration method like
create_tableandadd_column, an error will be raised instead of the option being silently ignored. Validation of the options will only be applied for new migrations that are created.Guo Xiang Tan, George Wambold
-
Update query log tags to use the SQLCommenter format by default. See #46179
To opt out of SQLCommenter-formatted query log tags, set
config.active_record.query_log_tags_format = :legacy. By default, this is set to:sqlcommenter.Modulitos and Iheanyi
-
Allow any ERB in the database.yml when creating rake tasks.
Any ERB can be used in
database.ymleven if it accesses environment configurations.Deprecates
config.active_record.suppress_multiple_database_warning.Eike Send
-
Add table to error for duplicate column definitions.
If a migration defines duplicate columns for a table, the error message shows which table it concerns.
Petrik de Heus
-
Fix erroneous nil default precision on virtual datetime columns.
Prior to this change, virtual datetime columns did not have the same default precision as regular datetime columns, resulting in the following being erroneously equivalent:
t.virtual :name, type: datetime, as: "expression" t.virtual :name, type: datetime, precision: nil, as: "expression"This change fixes the default precision lookup, so virtual and regular datetime column default precisions match.
Sam Bostock
-
Use connection from
#with_raw_connectionin#quote_string.This ensures that the string quoting is wrapped in the reconnect and retry logic that
#with_raw_connectionoffers.Adrianna Chang
-
Add
expires_atoption tosigned_id.Shouichi Kamiya
-
Allow applications to set retry deadline for query retries.
Building on the work done in #44576 and #44591, we extend the logic that automatically reconnects database connections to take into account a timeout limit. We won't retry a query if a given amount of time has elapsed since the query was first attempted. This value defaults to nil, meaning that all retryable queries are retried regardless of time elapsed, but this can be changed via the
retry_deadlineoption in the database config.Adrianna Chang
-
Fix a case where the query cache can return wrong values. See #46044
Aaron Patterson
-
Support MySQL's ssl-mode option for MySQLDatabaseTasks.
Verifying the identity of the database server requires setting the ssl-mode option to VERIFY_CA or VERIFY_IDENTITY. This option was previously ignored for MySQL database tasks like creating a database and dumping the structure.
Petrik de Heus
-
Move
ActiveRecord::InternalMetadatato an independent object.ActiveRecord::InternalMetadatano longer inherits fromActiveRecord::Baseand is now an independent object that should be instantiated with aconnection. This class is private and should not be used by applications directly. If you want to interact with the schema migrations table, please access it on the connection directly, for example:ActiveRecord::Base.connection.schema_migration.Eileen M. Uchitelle
-
Deprecate quoting
ActiveSupport::Durationas an integerUsing ActiveSupport::Duration as an interpolated bind parameter in a SQL string template is deprecated. To avoid this warning, you should explicitly convert the duration to a more specific database type. For example, if you want to use a duration as an integer number of seconds:
Record.where("duration = ?", 1.hour.to_i)If you want to use a duration as an ISO 8601 string:
Record.where("duration = ?", 1.hour.iso8601)Aram Greenman
-
Allow
QueryMethods#in_order_ofto order by a string column name.Post.in_order_of("id", [4,2,3,1]).to_a Post.joins(:author).in_order_of("authors.name", ["Bob", "Anna", "John"]).to_aIgor Kasyanchuk
-
Move
ActiveRecord::SchemaMigrationto an independent object.ActiveRecord::SchemaMigrationno longer inherits fromActiveRecord::Baseand is now an independent object that should be instantiated with aconnection. This class is private and should not be used by applications directly. If you want to interact with the schema migrations table, please access it on the connection directly, for example:ActiveRecord::Base.connection.schema_migration.Eileen M. Uchitelle
-
Deprecate
all_connection_poolsand makeconnection_pool_listmore explicit.Following on #45924
all_connection_poolsis now deprecated.connection_pool_listwill either take an explicit role or applications can opt into the new behavior by passing:all.Eileen M. Uchitelle
-
Fix connection handler methods to operate on all pools.
active_connections?,clear_active_connections!,clear_reloadable_connections!,clear_all_connections!, andflush_idle_connections!now operate on all pools by default. Previously they would default to using thecurrent_roleor:writingrole unless specified.Eileen M. Uchitelle
-
Allow ActiveRecord::QueryMethods#select to receive hash values.
Currently,
selectmight receive only raw sql and symbols to define columns and aliases to select.With this change we can provide
hashas argument, for example:Post.joins(:comments).select(posts: [:id, :title, :created_at], comments: [:id, :body, :author_id]) #=> "SELECT \"posts\".\"id\", \"posts\".\"title\", \"posts\".\"created_at\", \"comments\".\"id\", \"comments\".\"body\", \"comments\".\"author_id\" # FROM \"posts\" INNER JOIN \"comments\" ON \"comments\".\"post_id\" = \"posts\".\"id\"" Post.joins(:comments).select(posts: { id: :post_id, title: :post_title }, comments: { id: :comment_id, body: :comment_body }) #=> "SELECT posts.id as post_id, posts.title as post_title, comments.id as comment_id, comments.body as comment_body # FROM \"posts\" INNER JOIN \"comments\" ON \"comments\".\"post_id\" = \"posts\".\"id\""Oleksandr Holubenko, Josef Šimánek, Jean Boussier
-
Adapts virtual attributes on
ActiveRecord::Persistence#becomes.When source and target classes have a different set of attributes adapts attributes such that the extra attributes from target are added.
class Person < ApplicationRecord end class WebUser < Person attribute :is_admin, :boolean after_initialize :set_admin def set_admin write_attribute(:is_admin, email =~ /@ourcompany\.com$/) end end person = Person.find_by(email: "email@ourcompany.com") person.respond_to? :is_admin # => false person.becomes(WebUser).is_admin? # => trueJacopo Beschi, Sampson Crowley
-
Fix
ActiveRecord::QueryMethods#in_order_ofto includenils, to match the behavior ofEnumerable#in_order_of.For example,
Post.in_order_of(:title, [nil, "foo"])will now include posts withniltitles, the same asPost.all.to_a.in_order_of(:title, [nil, "foo"]).fatkodima
-
Optimize
add_timestampsto use a single SQL statement.add_timestamps :my_tableNow results in the following SQL:
ALTER TABLE "my_table" ADD COLUMN "created_at" datetime(6) NOT NULL, ADD COLUMN "updated_at" datetime(6) NOT NULLIliana Hadzhiatanasova
-
Add
drop_enummigration command for PostgreSQLThis does the inverse of
create_enum. Before dropping an enum, ensure you have dropped columns that depend on it.Alex Ghiculescu
-
Adds support for
if_existsoption when removing a check constraint.The
remove_check_constraintmethod now accepts anif_existsoption. If set to true an error won't be raised if the check constraint doesn't exist.Margaret Parsa and Aditya Bhutani
-
find_or_create_bynow try to find a second time if it hits a unicity constraint.find_or_create_byalways has been inherently racy, either creating multiple duplicate records or failing withActiveRecord::RecordNotUniquedepending on whether a proper unicity constraint was set.create_or_find_bywas introduced for this use case, however it's quite wasteful when the record is expected to exist most of the time, as INSERT require to send more data than SELECT and require more work from the database. Also on some databases it can actually consume a primary key increment which is undesirable.So for case where most of the time the record is expected to exist,
find_or_create_bycan be made race-condition free by re-trying thefindif thecreatefailed withActiveRecord::RecordNotUnique. This assumes that the table has the proper unicity constraints, if not,find_or_create_bywill still lead to duplicated records.Jean Boussier, Alex Kitchens
-
Introduce a simpler constructor API for ActiveRecord database adapters.
Previously the adapter had to know how to build a new raw connection to support reconnect, but also expected to be passed an initial already- established connection.
When manually creating an adapter instance, it will now accept a single config hash, and only establish the real connection on demand.
Matthew Draper
-
Avoid redundant
SELECT 1connection-validation query during DB pool checkout when possible.If the first query run during a request is known to be idempotent, it can be used directly to validate the connection, saving a network round-trip.
Matthew Draper
-
Automatically reconnect broken database connections when safe, even mid-request.
When an error occurs while attempting to run a known-idempotent query, and not inside a transaction, it is safe to immediately reconnect to the database server and try again, so this is now the default behavior.
This new default should always be safe -- to support that, it's consciously conservative about which queries are considered idempotent -- but if necessary it can be disabled by setting the
connection_retriesconnection option to0.Matthew Draper
-
Avoid removing a PostgreSQL extension when there are dependent objects.
Previously, removing an extension also implicitly removed dependent objects. Now, this will raise an error.
You can force removing the extension:
disable_extension :citext, force: :cascadeFixes #29091.
fatkodima
-
Allow nested functions as safe SQL string
Michael Siegfried
-
Allow
destroy_association_async_job=to be configured with a class string instead of a constant.Defers an autoloading dependency between
ActiveRecord::BaseandActiveJob::Baseand moves the configuration ofActiveRecord::DestroyAssociationAsyncJobfrom ActiveJob to ActiveRecord.Deprecates
ActiveRecord::ActiveJobRequiredErrorand now raises aNameErrorif the job class is unloadable or anActiveRecord::ConfigurationErrorifdependent: :destroy_asyncis declared on an association but there is no job class configured.Ben Sheldon
-
Fix
ActiveRecord::Storeto serialize as a regular HashPreviously it would serialize as an
ActiveSupport::HashWithIndifferentAccesswhich is wasteful and cause problem with YAML safe_load.Jean Boussier
-
Add
timestamptzas a time zone aware type for PostgreSQLThis is required for correctly parsing
timestamp with time zonevalues in your database.If you don't want this, you can opt out by adding this initializer:
ActiveRecord::Base.time_zone_aware_types -= [:timestamptz]Alex Ghiculescu
-
Add new
ActiveRecord::Base.generates_token_forAPI.Currently,
signed_idfulfills the role of generating tokens for e.g. resetting a password. However, signed IDs cannot reflect record state, so if a token is intended to be single-use, it must be tracked in a database at least until it expires.With
generates_token_for, a token can embed data from a record. When using the token to fetch the record, the data from the token and the current data from the record will be compared. If the two do not match, the token will be treated as invalid, the same as if it had expired. For example:class User < ActiveRecord::Base has_secure_password generates_token_for :password_reset, expires_in: 15.minutes do # A password's BCrypt salt changes when the password is updated. # By embedding (part of) the salt in a token, the token will # expire when the password is updated. BCrypt::Password.new(password_digest).salt[-10..] end end user = User.first token = user.generate_token_for(:password_reset) User.find_by_token_for(:password_reset, token) # => user user.update!(password: "new password") User.find_by_token_for(:password_reset, token) # => nilJonathan Hefner
-
Optimize Active Record batching for whole table iterations.
Previously,
in_batchesgot all the ids and constructed anIN-based query for each batch. When iterating over the whole tables, this approach is not optimal as it loads unneeded ids andINqueries with lots of items are slow.Now, whole table iterations use range iteration (
id >= x AND id <= y) by default which can make iteration several times faster. E.g., tested on a PostgreSQL table with 10 million records: querying (253svs30s), updating (288svs124s), deleting (268svs83s).Only whole table iterations use this style of iteration by default. You can disable this behavior by passing
use_ranges: false. If you iterate over the table and the only condition is, e.g.,archived_at: nil(and only a tiny fraction of the records are archived), it makes sense to opt in to this approach:Project.where(archived_at: nil).in_batches(use_ranges: true) do |relation| # do something endSee #45414 for more details.
fatkodima
-
.withquery method added. Construct common table expressions with ease and getActiveRecord::Relationback.Post.with(posts_with_comments: Post.where("comments_count > ?", 0)) # => ActiveRecord::Relation # WITH posts_with_comments AS (SELECT * FROM posts WHERE (comments_count > 0)) SELECT * FROM postsVlado Cingel
-
Don't establish a new connection if an identical pool exists already.
Previously, if
establish_connectionwas called on a class that already had an established connection, the existing connection would be removed regardless of whether it was the same config. Now if a pool is found with the same values as the new connection, the existing connection will be returned instead of creating a new one.This has a slight change in behavior if application code is depending on a new connection being established regardless of whether it's identical to an existing connection. If the old behavior is desirable, applications should call
ActiveRecord::Base#remove_connectionbefore establishing a new one. Callingestablish_connectionwith a different config works the same way as it did previously.Eileen M. Uchitelle
-
Update
db:preparetask to load schema when an uninitialized database exists, and dump schema after migrations.Ben Sheldon
-
Fix supporting timezone awareness for
tsrangeandtstzrangearray columns.# In database migrations add_column :shops, :open_hours, :tsrange, array: true # In app config ActiveRecord::Base.time_zone_aware_types += [:tsrange] # In the code times are properly converted to app time zone Shop.create!(open_hours: [Time.current..8.hour.from_now])Wojciech Wnętrzak
-
Introduce strategy pattern for executing migrations.
By default, migrations will use a strategy object that delegates the method to the connection adapter. Consumers can implement custom strategy objects to change how their migrations run.
Adrianna Chang
-
Add adapter option disallowing foreign keys
This adds a new option to be added to
database.ymlwhich enables skipping foreign key constraints usage even if the underlying database supports them.Usage:
development: <<: *default database: storage/development.sqlite3 foreign_keys: falsePaulo Barros
-
Add configurable deprecation warning for singular associations
This adds a deprecation warning when using the plural name of a singular associations in
where. It is possible to opt into the new more performant behavior withconfig.active_record.allow_deprecated_singular_associations_name = falseAdam Hess
-
Run transactional callbacks on the freshest instance to save a given record within a transaction.
When multiple Active Record instances change the same record within a transaction, Rails runs
after_commitorafter_rollbackcallbacks for only one of them.config.active_record.run_commit_callbacks_on_first_saved_instances_in_transactionwas added to specify how Rails chooses which instance receives the callbacks. The framework defaults were changed to use the new logic.When
config.active_record.run_commit_callbacks_on_first_saved_instances_in_transactionistrue, transactional callbacks are run on the first instance to save, even though its instance state may be stale.When it is
false, which is the new framework default starting with version 7.1, transactional callbacks are run on the instances with the freshest instance state. Those instances are chosen as follows:- In general, run transactional callbacks on the last instance to save a given record within the transaction.
- There are two exceptions:
- If the record is created within the transaction, then updated by
another instance,
after_create_commitcallbacks will be run on the second instance. This is instead of theafter_update_commitcallbacks that would naively be run based on that instance’s state. - If the record is destroyed within the transaction, then
after_destroy_commitcallbacks will be fired on the last destroyed instance, even if a stale instance subsequently performed an update (which will have affected 0 rows).
- If the record is created within the transaction, then updated by
another instance,
Cameron Bothner and Mitch Vollebregt
-
Enable strict strings mode for
SQLite3Adapter.Configures SQLite with a strict strings mode, which disables double-quoted string literals.
SQLite has some quirks around double-quoted string literals. It first tries to consider double-quoted strings as identifier names, but if they don't exist it then considers them as string literals. Because of this, typos can silently go unnoticed. For example, it is possible to create an index for a non existing column. See SQLite documentation for more details.
If you don't want this behavior, you can disable it via:
# config/application.rb config.active_record.sqlite3_adapter_strict_strings_by_default = falseFixes #27782.
fatkodima, Jean Boussier
-
Resolve issue where a relation cache_version could be left stale.
Previously, when
resetwas called on a relation object it did not reset the cache_versions ivar. This led to a confusing situation where despite having the correct data the relation still reported a stale cache_version.Usage:
developers = Developer.all developers.cache_version Developer.update_all(updated_at: Time.now.utc + 1.second) developers.cache_version # Stale cache_version developers.reset developers.cache_version # Returns the current correct cache_versionFixes #45341.
Austen Madden
-
Add support for exclusion constraints (PostgreSQL-only).
add_exclusion_constraint :invoices, "daterange(start_date, end_date) WITH &&", using: :gist, name: "invoices_date_overlap" remove_exclusion_constraint :invoices, name: "invoices_date_overlap"See PostgreSQL's
CREATE TABLE ... EXCLUDE ...documentation for more on exclusion constraints.Alex Robbin
-
change_column_nullraises if a non-boolean argument is providedPreviously if you provided a non-boolean argument,
change_column_nullwould treat it as truthy and make your column nullable. This could be surprising, so now the input must be eithertrueorfalse.change_column_null :table, :column, true # good change_column_null :table, :column, false # good change_column_null :table, :column, from: true, to: false # raises (previously this made the column nullable)Alex Ghiculescu
-
Enforce limit on table names length.
Fixes #45130.
fatkodima
-
Adjust the minimum MariaDB version for check constraints support.
Eddie Lebow
-
Fix Hstore deserialize regression.
edsharp
-
Add validity for PostgreSQL indexes.
connection.index_exists?(:users, :email, valid: true) connection.indexes(:users).select(&:valid?)fatkodima
-
Fix eager loading for models without primary keys.
Anmol Chopra, Matt Lawrence, and Jonathan Hefner
-
Avoid validating a unique field if it has not changed and is backed by a unique index.
Previously, when saving a record, Active Record will perform an extra query to check for the uniqueness of each attribute having a
uniquenessvalidation, even if that attribute hasn't changed. If the database has the corresponding unique index, then this validation can never fail for persisted records, and we could safely skip it.fatkodima
-
Stop setting
sql_auto_is_nullSince version 5.5 the default has been off, we no longer have to manually turn it off.
Adam Hess
-
Fix
touchto raise an error for readonly columns.fatkodima
-
Add ability to ignore tables by regexp for SQL schema dumps.
ActiveRecord::SchemaDumper.ignore_tables = [/^_/]fatkodima
-
Avoid queries when performing calculations on contradictory relations.
Previously calculations would make a query even when passed a contradiction, such as
User.where(id: []).count. We no longer perform a query in that scenario.This applies to the following calculations:
count,sum,average,minimumandmaximumLuan Vieira, John Hawthorn and Daniel Colson
-
Allow using aliased attributes with
insert_all/upsert_all.class Book < ApplicationRecord alias_attribute :title, :name end Book.insert_all [{ title: "Remote", author_id: 1 }], returning: :titlefatkodima
-
Support encrypted attributes on columns with default db values.
This adds support for encrypted attributes defined on columns with default values. It will encrypt those values at creation time. Before, it would raise an error unless
config.active_record.encryption.support_unencrypted_datawas true.Jorge Manrubia and Dima Fatko
-
Allow overriding
reading_request?inDatabaseSelector::ResolverThe default implementation checks if a request is a
get?orhead?, but you can now change it to anything you like. If the method returns true,Resolver#readgets called meaning the request could be served by the replica database.Alex Ghiculescu
-
Remove
ActiveRecord.legacy_connection_handling.Eileen M. Uchitelle
-
rails db:schema:{dump,load}now checksENV["SCHEMA_FORMAT"]before configSince
rails db:structure:{dump,load}was deprecated there wasn't a simple way to dump a schema to both SQL and Ruby formats. You can now do this with an environment variable. For example:SCHEMA_FORMAT=sql rake db:schema:dumpAlex Ghiculescu
-
Fixed MariaDB default function support.
Defaults would be written wrong in "db/schema.rb" and not work correctly if using
db:schema:load. Further more the function name would be added as string content when saving new records.kaspernj
-
Add
active_record.destroy_association_async_batch_sizeconfigurationThis allows applications to specify the maximum number of records that will be destroyed in a single background job by the
dependent: :destroy_asyncassociation option. By default, the current behavior will remain the same: when a parent record is destroyed, all dependent records will be destroyed in a single background job. If the number of dependent records is greater than this configuration, the records will be destroyed in multiple background jobs.Nick Holden
-
Fix
remove_foreign_keywith:if_existsoption when foreign key actually exists.fatkodima
-
Remove
--no-commentsflag in structure dumps for PostgreSQLThis broke some apps that used custom schema comments. If you don't want comments in your structure dump, you can use:
ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-comments']Alex Ghiculescu
-
Reduce the memory footprint of fixtures accessors.
Until now fixtures accessors were eagerly defined using
define_method. So the memory usage was directly dependent of the number of fixtures and test suites.Instead fixtures accessors are now implemented with
method_missing, so they incur much less memory and CPU overhead.Jean Boussier
-
Fix
config.active_record.destroy_association_async_jobconfigurationconfig.active_record.destroy_association_async_jobshould allow applications to specify the job that will be used to destroy associated records in the background forhas_manyassociations with thedependent: :destroy_asyncoption. Previously, that was ignored, which meant the defaultActiveRecord::DestroyAssociationAsyncJobalways destroyed records in the background.Nick Holden
-
Fix
change_column_commentto preserve column's AUTO_INCREMENT in the MySQL adapterfatkodima
-
Fix quoting of
ActiveSupport::DurationandRationalnumbers in the MySQL adapter.Kevin McPhillips
-
Allow column name with COLLATE (e.g., title COLLATE "C") as safe SQL string
Shugo Maeda
-
Permit underscores in the VERSION argument to database rake tasks.
Eddie Lebow
-
Reversed the order of
INSERTstatements instructure.sqldumpsThis should decrease the likelihood of merge conflicts. New migrations will now be added at the top of the list.
For existing apps, there will be a large diff the next time
structure.sqlis generated.Alex Ghiculescu, Matt Larraz
-
Fix PG.connect keyword arguments deprecation warning on ruby 2.7
Fixes #44307.
Nikita Vasilevsky
-
Fix dropping DB connections after serialization failures and deadlocks.
Prior to 6.1.4, serialization failures and deadlocks caused rollbacks to be issued for both real transactions and savepoints. This breaks MySQL which disallows rollbacks of savepoints following a deadlock.
6.1.4 removed these rollbacks, for both transactions and savepoints, causing the DB connection to be left in an unknown state and thus discarded.
These rollbacks are now restored, except for savepoints on MySQL.
Thomas Morgan
-
Make
ActiveRecord::ConnectionPoolFiber-safeWhen
ActiveSupport::IsolatedExecutionState.isolation_levelis set to:fiber, the connection pool now supports multiple Fibers from the same Thread checking out connections from the pool.Alex Matchneer
-
Add
update_attribute!toActiveRecord::PersistenceSimilar to
update_attribute, but raisesActiveRecord::RecordNotSavedwhen abefore_*callback throws:abort.class Topic < ActiveRecord::Base before_save :check_title def check_title throw(:abort) if title == "abort" end end topic = Topic.create(title: "Test Title") # #=> #<Topic title: "Test Title"> topic.update_attribute!(:title, "Another Title") # #=> #<Topic title: "Another Title"> topic.update_attribute!(:title, "abort") # raises ActiveRecord::RecordNotSavedDrew Tempelmeyer
-
Avoid loading every record in
ActiveRecord::Relation#pretty_print# Before pp Foo.all # Loads the whole table. # After pp Foo.all # Shows 10 items and an ellipsis.Ulysse Buonomo
-
Change
QueryMethods#in_order_ofto drop records not listed in values.in_order_ofnow filters down to the values provided, to match the behavior of theEnumerableversion.Kevin Newton
-
Allow named expression indexes to be revertible.
Previously, the following code would raise an error in a reversible migration executed while rolling back, due to the index name not being used in the index removal.
add_index(:settings, "(data->'property')", using: :gin, name: :index_settings_data_property)Fixes #43331.
Oliver Günther
-
Fix incorrect argument in PostgreSQL structure dump tasks.
Updating the
--no-commentargument added in Rails 7 to the correct--no-commentsargument.Alex Dent
-
Fix migration compatibility to create SQLite references/belongs_to column as integer when migration version is 6.0.
Reference/belongs_to in migrations with version 6.0 were creating columns as bigint instead of integer for the SQLite Adapter.
Marcelo Lauxen
-
Fix
QueryMethods#in_order_ofto handle empty order list.Post.in_order_of(:id, []).to_aAlso more explicitly set the column as secondary order, so that any other value is still ordered.
Jean Boussier
-
Fix quoting of column aliases generated by calculation methods.
Since the alias is derived from the table name, we can't assume the result is a valid identifier.
class Test < ActiveRecord::Base self.table_name = '1abc' end Test.group(:id).count # syntax error at or near "1" (ActiveRecord::StatementInvalid) # LINE 1: SELECT COUNT(*) AS count_all, "1abc"."id" AS 1abc_id FROM "1...Jean Boussier
-
Add
authenticate_bywhen usinghas_secure_password.authenticate_byis intended to replace code like the following, which returns early when a user with a matching email is not found:User.find_by(email: "...")&.authenticate("...")Such code is vulnerable to timing-based enumeration attacks, wherein an attacker can determine if a user account with a given email exists. After confirming that an account exists, the attacker can try passwords associated with that email address from other leaked databases, in case the user re-used a password across multiple sites (a common practice). Additionally, knowing an account email address allows the attacker to attempt a targeted phishing ("spear phishing") attack.
authenticate_byaddresses the vulnerability by taking the same amount of time regardless of whether a user with a matching email is found:User.authenticate_by(email: "...", password: "...")Jonathan Hefner
Action View
-
Introduce
ActionView::TestCase.register_parserregister_parser :rss, -> rendered { RSS::Parser.parse(rendered) } test "renders RSS" do article = Article.create!(title: "Hello, world") render formats: :rss, partial: article assert_equal "Hello, world", rendered.rss.items.last.title endBy default, register parsers for
:htmland:json.Sean Doyle
-
Fix
simple_formatwith blankwrapper_tagoption returns plain html tagBy default
simple_formatmethod returns the text wrapped with<p>. But if we explicitly specify thewrapper_tag: nilin the options, it returns the text wrapped with<></>tag.Before:
simple_format("Hello World", {}, { wrapper_tag: nil }) # <>Hello World</>After:
simple_format("Hello World", {}, { wrapper_tag: nil }) # <p>Hello World</p> `
See https://github.com/rails/rails/releases/tag/v7.0.9 for information about this release.
Active Support
-
Fix
TimeWithZonestill using deprecated#to_swhenENVorconfigto disable it are set.Hartley McGuire
-
Fix CacheStore#write_multi when using a distributed Redis cache with a connection pool.
Fixes #48938.
Jonathan del Strother
Active Model
- No changes.
Active Record
-
Fix
change_columnnot settingprecision: 6ondatetimecolumns when using 7.0+ Migrations and SQLite.Hartley McGuire
-
Fix unscope is not working in specific case
Before:
Post.where(id: 1...3).unscope(where: :id).to_sql # "SELECT `posts`.* FROM `posts` WHERE `posts`.`id` >= 1 AND `posts`.`id` < 3"After:
Post.where(id: 1...3).unscope(where: :id).to_sql # "SELECT `posts`.* FROM `posts`"Fixes #48094.
Kazuya Hatanaka
-
Fix associations to a STI model including a
class_nameparameterclass Product < ApplicationRecord has_many :requests, as: :requestable, class_name: "ProductRequest", dependent: :destroy end # STI tables class Request < ApplicationRecord belongs_to :requestable, polymorphic: true validate :request_type, presence: true end class ProductRequest < Request belongs_to :user endAccessing such association would lead to:
table_metadata.rb:22:in `has_column?': undefined method `key?' for nil:NilClass (NoMethodError)Romain Filinto
-
Fix
change_tablesetting datetime precision for 6.1 MigrationsHartley McGuire
-
Fix change_column setting datetime precision for 6.1 Migrations
Hartley McGuire
Action View
-
Fix
form_formissing the hidden_methodinput for models with a namespaced route.Hartley McGuire
-
Fix
render collection: @records, cache: trueinsidejbuildertemplatesThe previous fix that shipped in
7.0.7assumed template fragments are always strings, this isn't true withjbuilder.Jean Boussier
Action Pack
-
Fix
HostAuthorizationpotentially displaying the value of the X_FORWARDED_HOST header when the HTTP_HOST header is being blocked.Hartley McGuire, Daniel Schlosser
Active Job
-
Fix Active Job log message to correctly report a job failed to enqueue when the adapter raises an
ActiveJob::EnqueueError.Ben Sheldon
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Omit
webdriversgem dependency fromGemfiletemplateSean Doyle
Active Support
-
Fix
Cache::NullStorewith local caching for repeated reads.fatkodima
-
Fix
to_swith no arguments not respecting custom:defaultformatsHartley McGuire
-
Fix
ActiveSupport::Inflector.humanize(nil)raisingNoMethodError: undefined method `end_with?' for nil:NilClass.James Robinson
-
Fix
Enumerable#sumforEnumerator#lazy.fatkodima, Matthew Draper, Jonathan Hefner
-
Improve error message when EventedFileUpdateChecker is used without a compatible version of the Listen gem
Hartley McGuire
Active Model
-
Error.full_message now strips ":base" from the message.
zzak
-
Add a load hook for
ActiveModel::Model(namedactive_model) to match the load hook forActiveRecord::Baseand allow for overriding aspects of theActiveModel::Modelclass.
Active Record
-
Restores functionality to the missing method when using enums and fixes.
paulreece
-
Fix
StatementCache::Substitutewith serialized type.ywenc
-
Fix
:db_runtimeon notification payload when application have multiple databases.Eileen M. Uchitelle
-
Correctly dump check constraints for MySQL 8.0.16+.
Steve Hill
-
Fix
ActiveRecord::QueryMethods#in_order_ofto includenils, to match the behavior ofEnumerable#in_order_of.For example,
Post.in_order_of(:title, [nil, "foo"])will now include posts withniltitles, the same asPost.all.to_a.in_order_of(:title, [nil, "foo"]).fatkodima
-
Revert "Fix autosave associations with validations added on
:baseof the associated objects."This change intended to remove the :base attribute from the message, but broke many assumptions which key these errors were stored.
zzak
-
Fix
#previously_new_record?to return true for destroyed records.Before, if a record was created and then destroyed,
#previously_new_record?would return true. Now, any UPDATE or DELETE to a record is considered a change, and will result in#previously_new_record?returning false.Adrianna Chang
-
Revert breaking changes to
has_onerelationship deleting the old record before the new one is validated.zzak
-
Fix support for Active Record instances being uses in queries.
As of
7.0.5, query arguments were deep duped to avoid mutations impacting the query cache, but this had the adverse effect to clearing the primary key when the query argument contained anActiveRecord::Baseinstance.This broke the
noticedgem.Jean Boussier
Action View
-
Fix
render collection: @records, cache: trueto cache fragments as bare stringsPreviously it would incorrectly cache them as Action View buffers.
Jean Boussier
-
Don't double-encode nested
field_idandfield_nameindex valuesPass
index: @optionsas a default keyword argument tofield_idandfield_nameview helper methods.Sean Doyle
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Update default scaffold templates to set 303 (See Other) as status code on redirect for the update action for XHR requests other than GET or POST to avoid issues (e.g browsers trying to follow the redirect using the original request method resulting in double PATCH/PUT)
Guillermo Iguaran
Active Support
-
Fix
EncryptedConfigurationreturning incorrect values for someHashmethodsHartley McGuire
-
Fix arguments being destructed
Enumerable#many?with block.Andrew Novoselac
-
Fix humanize for strings ending with id.
fatkodima
Active Model
- No changes.
Active Record
-
Fix autosave associations with validations added on
:baseof the associated objects.fatkodima
-
Fix result with anonymous PostgreSQL columns of different type from json.
Oleksandr Avoiants
-
Preserve timestamp when setting an
ActiveSupport::TimeWithZonevalue totimestamptzattribute.fatkodima
-
Fix where on association with has_one/has_many polymorphic relations.
Before:
Treasure.where(price_estimates: PriceEstimate.all) #=> SELECT (...) WHERE "treasures"."id" IN (SELECT "price_estimates"."estimate_of_id" FROM "price_estimates")Later:
Treasure.where(price_estimates: PriceEstimate.all) #=> SELECT (...) WHERE "treasures"."id" IN (SELECT "price_estimates"."estimate_of_id" FROM "price_estimates" WHERE "price_estimates"."estimate_of_type" = 'Treasure')Lázaro Nixon
-
Fix decrementing counter caches on optimistically locked record deletion
fatkodima
-
Ensure binary-destined values have binary encoding during type cast.
Matthew Draper
-
Preserve existing column default functions when altering table in SQLite.
fatkodima
-
Remove table alias added when using
where.missingorwhere.associated.fatkodima
-
Fix
Enumerable#in_order_ofto only flatten first level to preserve nesting.Miha Rekar
Action View
- No changes.
Action Pack
- No changes.
Active Job
-
Fix error Active Job passed class with
permitted?.Alex Baldwin
Action Mailer
- No changes.
Action Cable
-
Fix Action Cable Redis configuration with sentinels.
Dmitriy Ivliev
Active Storage
-
Fix retrieving rotation value from FFmpeg on version 5.0+.
In FFmpeg version 5.0+ the rotation value has been removed from tags. Instead the value can be found in side_data_list. Along with this update it's possible to have values of -90, -270 to denote the video has been rotated.
Haroon Ahmed
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Avoid escaping paths when editing credentials.
Jonathan Hefner
Active Support
-
Fixes TimeWithZone ArgumentError.
Niklas Häusele
Active Model
- No changes.
Active Record
-
Type cast
#attribute_changed?:fromand:tooptions.Andrew Novoselac
-
Fix
index_exists?when column is an array.Eileen M. Uchitelle
-
Handle
Dateobjects for PostgreSQLtimestamptzcolumns.Alex Ghiculescu
-
Fix collation for changing column to non-string.
Hartley McGuire
-
Map through subtype in
PostgreSQL::OID::Array.Jonathan Hefner
-
Store correct environment in
internal_metadatawhen run railsdb:prepare.fatkodima
-
Make sure
ActiveRecord::Relation#sumworks with objects that implement#coercewithout deprecation.Alex Ghiculescu
-
Fix retrieving foreign keys referencing tables named like keywords in PostgreSQL and MySQL.
fatkodima
-
Support UUIDs in Disable Joins.
Samuel Cochran
-
Fix Active Record's explain for queries starting with comments.
fatkodima
-
Fix incorrectly preloading through association records when middle association has been loaded.
Joshua Young
-
Fix where.missing and where.associated for parent/child associations.
fatkodima
-
Fix Enumerable#in_order_of to preserve duplicates.
fatkodima
-
Fix autoincrement on primary key for mysql.
Eileen M. Uchitelle
-
Restore ability to redefine column in
create_tablefor Rails 5.2 migrations.fatkodima
-
Fix schema cache dumping of virtual columns.
fatkodima
-
Fix Active Record grouped calculations on joined tables on column present in both tables.
fatkodima
-
Fix mutation detection for serialized attributes backed by binary columns.
Jean Boussier
-
Fix a bug where using groups and counts with long table names would return incorrect results.
Shota Toguchi, Yusaku Ono
-
Fix erroneous nil default precision on virtual datetime columns.
Prior to this change, virtual datetime columns did not have the same default precision as regular datetime columns, resulting in the following being erroneously equivalent:
t.virtual :name, type: datetime, as: "expression" t.virtual :name, type: datetime, precision: nil, as: "expression"This change fixes the default precision lookup, so virtual and regular datetime column default precisions match.
Sam Bostock
-
Fix a case where the query cache can return wrong values. See #46044
Aaron Patterson
Action View
-
FormBuilder#idfinds id set byform_forandform_with.Matt Polito
-
Allow all available locales for template lookups.
Ben Dilley
-
Choices of
selectcan optionally contain html attributes as the last element of the child arrays when using grouped/nested collections<%= form.select :foo, [["North America", [["United States","US"],["Canada","CA"]], { disabled: "disabled" }]] %> # => <select><optgroup label="North America" disabled="disabled"><option value="US">United States</option><option value="CA">Canada</option></optgroup></select>Chris Gunther
Action Pack
-
Do not return CSP headers for 304 Not Modified responses.
Tobias Kraze
-
Fix
EtagWithFlashwhen there is noFlashmiddleware available.fatkodima
-
Fix content-type header with
send_stream.Elliot Crosby-McCullough
-
Address Selenium
:capabilitiesdeprecation warning.Ron Shinall
-
Fix cookie domain for domain: all on two letter single level TLD.
John Hawthorn
-
Don't double log the
controller,action, ornamespaced_controllerwhen usingActiveRecord::QueryLogPreviously if you set
config.active_record.query_log_tagsto an array that included:controller,:namespaced_controller, or:action, that item would get logged twice. This bug has been fixed.Alex Ghiculescu
-
Rescue
EOFErrorexception fromrackon a multipart request.Nikita Vasilevsky
-
Rescue
JSON::ParserErrorin Cookies json deserializer to discards marshal dumps:Without this change, if
action_dispatch.cookies_serializeris set to:jsonand the app tries to read a:marshalserialized cookie, it would error out which wouldn't clear the cookie and force app users to manually clear it in their browser.(See #45127 for original bug discussion)
Nathan Bardoux
Active Job
-
Make delayed job
display_namefailsafe.codez
-
Don't double log the
jobwhen usingActiveRecord::QueryLogPreviously if you set
config.active_record.query_log_tagsto an array that included:job, the job name would get logged twice. This bug has been fixed.Alex Ghiculescu
Action Mailer
- No changes.
Action Cable
-
Restore Action Cable Redis pub/sub listener on connection failure.
Vladimir Dementyev
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
-
Fix
ActionText::Attachable#as_json.Alexandre Ruban
Railties
-
Add puma app server to Gemfile in order to start test/dummy.
Donapieppo
-
Rails console now disables
IRB's autocompletion feature in production by default.Setting
IRB_USE_AUTOCOMPLETE=truecan override this default.Stan Lo
-
Send 303 See Other status code back for the destroy action on newly generated scaffold controllers.
Tony Drake
Active Support
-
Redis cache store is now compatible with redis-rb 5.0.
Jean Boussier
-
Fix
NoMethodErroron customActiveSupport::Deprecationbehavior.ActiveSupport::Deprecation.behavior=was supposed to accept any object that responds tocall, but in fact its internal implementation assumed that this object could respond toarity, so it was restricted to onlyProcobjects.This change removes this
arityrestriction of custom behaviors.Ryo Nakamura
Active Model
-
Handle name clashes in attribute methods code generation cache.
When two distinct attribute methods would generate similar names, the first implementation would be incorrectly re-used.
class A attribute_method_suffix "_changed?" define_attribute_methods :x end class B attribute_method_suffix "?" define_attribute_methods :x_changed endJean Boussier
Active Record
-
Symbol is allowed by default for YAML columns
Étienne Barrié
-
Fix
ActiveRecord::Storeto serialize as a regular HashPreviously it would serialize as an
ActiveSupport::HashWithIndifferentAccesswhich is wasteful and cause problem with YAML safe_load.Jean Boussier
-
Add
timestamptzas a time zone aware type for PostgreSQLThis is required for correctly parsing
timestamp with time zonevalues in your database.If you don't want this, you can opt out by adding this initializer:
ActiveRecord::Base.time_zone_aware_types -= [:timestamptz]Alex Ghiculescu
-
Fix supporting timezone awareness for
tsrangeandtstzrangearray columns.# In database migrations add_column :shops, :open_hours, :tsrange, array: true # In app config ActiveRecord::Base.time_zone_aware_types += [:tsrange] # In the code times are properly converted to app time zone Shop.create!(open_hours: [Time.current..8.hour.from_now])Wojciech Wnętrzak
-
Resolve issue where a relation cache_version could be left stale.
Previously, when
resetwas called on a relation object it did not reset the cache_versions ivar. This led to a confusing situation where despite having the correct data the relation still reported a stale cache_version.Usage:
developers = Developer.all developers.cache_version Developer.update_all(updated_at: Time.now.utc + 1.second) developers.cache_version # Stale cache_version developers.reset developers.cache_version # Returns the current correct cache_versionFixes #45341.
Austen Madden
-
Fix
load_asyncwhen called on an association proxy.Calling
load_asyncdirectly an association would schedule a query but never use it.comments = post.comments.load_async # schedule a query comments.to_a # perform an entirely new sync queryNow it does use the async query, however note that it doesn't cause the association to be loaded.
Jean Boussier
-
Fix eager loading for models without primary keys.
Anmol Chopra, Matt Lawrence, and Jonathan Hefner
-
rails db:schema:{dump,load}now checksENV["SCHEMA_FORMAT"]before configSince
rails db:structure:{dump,load}was deprecated there wasn't a simple way to dump a schema to both SQL and Ruby formats. You can now do this with an environment variable. For example:SCHEMA_FORMAT=sql rake db:schema:dumpAlex Ghiculescu
-
Fix Hstore deserialize regression.
edsharp
Action View
-
Guard against
ActionView::Helpers::FormTagHelper#field_namecalls with nilobject_namearguments. For example:<%= fields do |f| %> <%= f.field_name :body %> <% end %>Sean Doyle
-
Strings returned from
strip_tagsare correctly taggedhtml_safe?Because these strings contain no HTML elements and the basic entities are escaped, they are safe to be included as-is as PCDATA in HTML content. Tagging them as html-safe avoids double-escaping entities when being concatenated to a SafeBuffer during rendering.
Fixes rails/rails-html-sanitizer#124
Mike Dalessio
Action Pack
-
Prevent
ActionDispatch::ServerTimingfrom overwriting existing values inServer-Timing.Previously, if another middleware down the chain set
Server-Timingheader, it would overwritten byActionDispatch::ServerTiming.Jakub Malinowski
Active Job
-
Update
ActiveJob::QueueAdapters::QueAdapterto remove deprecation warning.Remove a deprecation warning introduced in que 1.2 to prepare for changes in que 2.0 necessary for Ruby 3 compatibility.
Damir Zekic and Adis Hasovic
Action Mailer
- No changes.
Action Cable
-
The Redis adapter is now compatible with redis-rb 5.0
Compatibility with redis-rb 3.x was dropped.
Jean Boussier
-
The Action Cable server is now mounted with
anchor: true.This means that routes that also start with
/cablewill no longer clash with Action Cable.Alex Ghiculescu
Active Storage
-
Fixes proxy downloads of files over 5MiB
Previously, trying to view and/or download files larger than 5mb stored in services like S3 via proxy mode could return corrupted files at around 5.2mb or cause random halts in the download. Now,
ActiveStorage::Blobs::ProxyControllercorrectly handles streaming these larger files from the service to the client without any issues.Fixes #44679
Felipe Raul
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
config.allow_concurrency = falsenow use aMonitorinstead of aMutexThis allows to enable
config.active_support.executor_around_test_caseeven whenconfig.allow_concurrencyis disabled.Jean Boussier
-
Skip Active Storage and Action Mailer if Active Job is skipped.
Étienne Barrié
-
Correctly check if frameworks are disabled when running app:update.
Étienne Barrié and Paulo Barros
-
Fixed
config.active_support.cache_format_versionnever being applied.Rails 7.0 shipped with a new serializer for Rails.cache, but the associated config wasn't working properly. Note that even after this fix, it can only be applied from the
application.rbfile.Alex Ghiculescu
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Some internal housekeeping on reloads could break custom
respond_to?methods in class objects that referenced reloadable constants. See #44125 for details.Xavier Noria
-
Fixed MariaDB default function support.
Defaults would be written wrong in "db/schema.rb" and not work correctly if using
db:schema:load. Further more the function name would be added as string content when saving new records.kaspernj
-
Fix
remove_foreign_keywith:if_existsoption when foreign key actually exists.fatkodima
-
Remove
--no-commentsflag in structure dumps for PostgreSQLThis broke some apps that used custom schema comments. If you don't want comments in your structure dump, you can use:
ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-comments']Alex Ghiculescu
-
Use the model name as a prefix when filtering encrypted attributes from logs.
For example, when encrypting
Person#nameit will addperson.nameas a filter parameter, instead of justname. This prevents unintended filtering of parameters with a matching name in other models.Jorge Manrubia
-
Fix quoting of
ActiveSupport::DurationandRationalnumbers in the MySQL adapter.Kevin McPhillips
-
Fix
change_column_commentto preserve column's AUTO_INCREMENT in the MySQL adapterfatkodima
Action View
-
Ensure models passed to
form_forattempt to callto_model.Sean Doyle
Action Pack
-
Allow relative redirects when
raise_on_open_redirectsis enabled.Tom Hughes
-
Fix
authenticate_with_http_basicto allow for missing password.Before Rails 7.0 it was possible to handle basic authentication with only a username.
authenticate_with_http_basic do |token, _| ApiClient.authenticate(token) endThis ability is restored.
Jean Boussier
-
Fix
content_security_policyreturning invalid directives.Directives such as
self,unsafe-evaland few others were not single quoted when the directive was the result of calling a lambda returning an array.content_security_policy do |policy| policy.frame_ancestors lambda { [:self, "https://example.com"] } endWith this fix the policy generated from above will now be valid.
Edouard Chin
-
Fix
skip_forgery_protectionto run without raising an error if forgery protection has not been enabled /verify_authenticity_tokenis not a defined callback.This fix prevents the Rails 7.0 Welcome Page (
/) from raising anArgumentErrorifdefault_protect_from_forgeryis false.Brad Trick
-
Fix
ActionController::Liveto copy the IsolatedExecutionState in the ephemeral thread.Since its inception
ActionController::Livehas been copying thread local variables to keep things such asCurrentAttributesset from middlewares working in the controller action.With the introduction of
IsolatedExecutionStatein 7.0, some of that global state was lost inActionController::Livecontrollers.Jean Boussier
-
Fix setting
trailing_slash: truein route definition.get '/test' => "test#index", as: :test, trailing_slash: true test_path() # => "/test/"Jean Boussier
Active Job
-
Add missing
bigdecimalrequire inActiveJob::ArgumentsCould cause
uninitialized constant ActiveJob::Arguments::BigDecimal (NameError)when loading Active Job in isolation.Jean Boussier
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Don't stream responses in redirect mode
Previously, both redirect mode and proxy mode streamed their responses which caused a new thread to be created, and could end up leaking connections in the connection pool. But since redirect mode doesn't actually send any data, it doesn't need to be streamed.
Luke Lau
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
If reloading and eager loading are both enabled, after a reload Rails eager loads again the application code.
Xavier Noria
-
Use
controller_class_pathinRails::Generators::NamedBase#route_urlThe
route_urlmethod now returns the correct path when generating a namespaced controller with a top-level model using--model-name.Previously, when running this command:
bin/rails generate scaffold_controller Admin/Post --model-name Postthe comments above the controller action would look like:
# GET /posts def index @posts = Post.all endafterwards, they now look like this:
# GET /admin/posts def index @posts = Post.all endFixes #44662.
Andrew White
Active Support
-
Fix
ActiveSupport::EncryptedConfigurationto be compatible with Psych 4Stephen Sugden
-
Improve
File.atomic_writeerror handling.Daniel Pepper
Active Model
-
Use different cache namespace for proxy calls
Models can currently have different attribute bodies for the same method names, leading to conflicts. Adding a new namespace
:active_model_proxyfixes the issue.Chris Salzberg
Active Record
-
Fix
PG.connectkeyword arguments deprecation warning on ruby 2.7.Nikita Vasilevsky
-
Fix the ability to exclude encryption params from being autofiltered.
Mark Gangl
-
Dump the precision for datetime columns following the new defaults.
Rafael Mendonça França
-
Make sure encrypted attributes are not being filtered twice.
Nikita Vasilevsky
-
Dump the database schema containing the current Rails version.
Since https://github.com/rails/rails/pull/42297, Rails now generate datetime columns with a default precision of 6. This means that users upgrading to Rails 7.0 from 6.1, when loading the database schema, would get the new precision value, which would not match the production schema.
To avoid this the schema dumper will generate the new format which will include the Rails version and will look like this:
ActiveRecord::Schema[7.0].defineWhen upgrading from Rails 6.1 to Rails 7.0, you can run the
rails app:updatetask that will set the current schema version to 6.1.Rafael Mendonça França
-
Fix parsing expression for PostgreSQL generated column.
fatkodima
-
Fix
Mysql2::Error: Commands out of sync; you can't run this command nowwhen bulk-inserting fixtures that exceedmax_allowed_packetconfiguration.Nikita Vasilevsky
-
Fix error when saving an association with a relation named
record.Dorian Marié
-
Fix
MySQL::SchemaDumperbehavior about datetime precision value.y0t4
-
Improve associated with no reflection error.
Nikolai
-
Fix PG.connect keyword arguments deprecation warning on ruby 2.7.
Fixes #44307.
Nikita Vasilevsky
-
Fix passing options to
check_constraintfromchange_table.Frederick Cheung
Action View
-
Ensure
preload_link_tagpreloads JavaScript modules correctly.Máximo Mussini
-
Fix
stylesheet_link_tagand similar helpers are being used to work in objects with aresponsemethod.dark-panda
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Revert the ability to pass
service_nameparam toDirectUploadsControllerwhich was introduced in 7.0.0.That change caused a lot of problems to upgrade Rails applications so we decided to remove it while in work in a more backwards compatible implementation.
Gannon McGibbon
-
Allow applications to opt out of precompiling Active Storage JavaScript assets.
jlestavel
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Active Support
-
Fix
Class#descendantsandDescendantsTracker#descendantscompatibility with Ruby 3.1.The native
Class#descendantswas reverted prior to Ruby 3.1 release, butClass#subclasseswas kept, breaking the feature detection.Jean Boussier
Active Model
- No changes.
Active Record
-
Change
QueryMethods#in_order_ofto drop records not listed in values.in_order_ofnow filters down to the values provided, to match the behavior of theEnumerableversion.Kevin Newton
-
Allow named expression indexes to be revertible.
Previously, the following code would raise an error in a reversible migration executed while rolling back, due to the index name not being used in the index removal.
add_index(:settings, "(data->'property')", using: :gin, name: :index_settings_data_property)Fixes #43331.
Oliver Günther
-
Better error messages when association name is invalid in the argument of
ActiveRecord::QueryMethods::WhereChain#missing.ykpythemind
-
Fix ordered migrations for single db in multi db environment.
Himanshu
-
Extract
on update CURRENT_TIMESTAMPfor mysql2 adapter.Kazuhiro Masuda
-
Fix incorrect argument in PostgreSQL structure dump tasks.
Updating the
--no-commentargument added in Rails 7 to the correct--no-commentsargument.Alex Dent
-
Fix schema dumping column default SQL values for sqlite3.
fatkodima
-
Correctly parse complex check constraint expressions for PostgreSQL.
fatkodima
-
Fix
timestamptzattributes on PostgreSQL handle blank inputs.Alex Ghiculescu
-
Fix migration compatibility to create SQLite references/belongs_to column as integer when migration version is 6.0.
Reference/belongs_to in migrations with version 6.0 were creating columns as bigint instead of integer for the SQLite Adapter.
Marcelo Lauxen
-
Fix joining through a polymorphic association.
Alexandre Ruban
-
Fix
QueryMethods#in_order_ofto handle empty order list.Post.in_order_of(:id, []).to_aAlso more explicitly set the column as secondary order, so that any other value is still ordered.
Jean Boussier
-
Fix
rails dbconsolefor 3-tier config.Eileen M. Uchitelle
-
Fix quoting of column aliases generated by calculation methods.
Since the alias is derived from the table name, we can't assume the result is a valid identifier.
class Test < ActiveRecord::Base self.table_name = '1abc' end Test.group(:id).count # syntax error at or near "1" (ActiveRecord::StatementInvalid) # LINE 1: SELECT COUNT(*) AS count_all, "1abc"."id" AS 1abc_id FROM "1...Jean Boussier
Action View
-
Fix
button_toto work with a hash parameter as URL.MingyuanQin
-
Fix
link_towith a model passed as an argument twice.Alex Ghiculescu
Action Pack
-
Fix
ActionController::Parametersmethods to keep the original logger context when creating a new copy of the original object.Yutaka Kamei
Active Job
-
Allow testing
discard_on/retry_on ActiveJob::DeserializationErrorPreviously in
perform_enqueued_jobs,deserialize_arguments_if_neededwas called before callingperform_now. When a record no longer exists and is serialized using GlobalID this led to raising anActiveJob::DeserializationErrorbefore reachingperform_nowcall. This behaviour makes difficult testing the jobdiscard_on/retry_onlogic.Now
deserialize_arguments_if_neededcall is postponed to whenperform_nowis called.Example:
class UpdateUserJob < ActiveJob::Base discard_on ActiveJob::DeserializationError def perform(user) # ... end end # In the test User.destroy_all assert_nothing_raised do perform_enqueued_jobs only: UpdateUserJob endJacopo Beschi
Action Mailer
-
Keep configuration of
smtp_settingsconsistent between 6.1 and 7.0.André Luis Leal Cardoso Junior
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Prevent duplicate entries in plugin Gemfile.
Jonathan Hefner
-
Fix asset pipeline errors for plugin dummy apps.
Jonathan Hefner
-
Fix generated route revocation.
Jonathan Hefner
-
Addresses an issue in which Sidekiq jobs could not reload certain namespaces.
See fxn/zeitwerk#198 for details.
Xavier Noria
-
Fix plugin generator to a plugin that pass all the tests.
Rafael Mendonça França
Action Cable
-
The Action Cable client now ensures successful channel subscriptions:
- The client maintains a set of pending subscriptions until either the server confirms the subscription or the channel is torn down.
- Rectifies the race condition where an unsubscribe is rapidly followed by a subscribe (on the same channel identifier) and the requests are handled out of order by the ActionCable server, thereby ignoring the subscribe command.
Daniel Spinosa
-
Compile ESM package that can be used directly in the browser as actioncable.esm.js.
DHH
-
Move action_cable.js to actioncable.js to match naming convention used for other Rails frameworks, and use JS console to communicate the deprecation.
DHH
-
Stop transpiling the UMD package generated as actioncable.js and drop the IE11 testing that relied on that.
DHH
-
Truncate broadcast logging messages.
J Smith
-
OpenSSL constants are now used for Digest computations.
Dirkjan Bussink
-
The Action Cable client now includes safeguards to prevent a "thundering herd" of client reconnects after server connectivity loss:
- The client will wait a random amount between 1x and 3x of the stale threshold after the server's last ping before making the first reconnection attempt.
- Subsequent reconnection attempts now use exponential backoff instead of logarithmic backoff. To allow the delay between reconnection attempts to increase slowly at first, the default exponentiation base is < 2.
- Random jitter is applied to each delay between reconnection attempts.
Jonathan Hefner
Action Mailbox
-
Removed deprecated environment variable
MAILGUN_INGRESS_API_KEY.Rafael Mendonça França
-
Removed deprecated
Rails.application.credentials.action_mailbox.mailgun_api_key.Rafael Mendonça França
-
Add
attachmentsto the list of permitted parameters for inbound emails conductor.When using the conductor to test inbound emails with attachments, this prevents an unpermitted parameter warning in default configurations, and prevents errors for applications that set:
config.action_controller.action_on_unpermitted_parameters = :raiseDavid Jones, Dana Henke
-
Add ability to configure ActiveStorage service for storing email raw source.
# config/storage.yml incoming_emails: service: Disk root: /secure/dir/for/emails/onlyconfig.action_mailbox.storage_service = :incoming_emailsYurii Rashkovskii
-
Add ability to incinerate an inbound message through the conductor interface.
Santiago Bartesaghi
-
OpenSSL constants are now used for Digest computations.
Dirkjan Bussink
Action Mailer
-
Remove deprecated
ActionMailer::DeliveryJobandActionMailer::Parameterized::DeliveryJobin favor ofActionMailer::MailDeliveryJob.Rafael Mendonça França
-
email_address_with_namereturns just the address if name is blank.Thomas Hutterer
-
Configures a default of 5 for both
open_timeoutandread_timeoutfor SMTP Settings.André Luis Leal Cardoso Junior
Action Pack
-
Deprecate
Rails.application.config.action_controller.urlsafe_csrf_tokens. This config is now always enabled.Étienne Barrié
-
Instance variables set in requests in a
ActionController::TestCaseare now cleared before the next requestThis means if you make multiple requests in the same test, instance variables set in the first request will not persist into the second one. (It's not recommended to make multiple requests in the same test.)
Alex Ghiculescu
-
Rails.application.executorhooks can now be called around every request in aActionController::TestCaseThis helps to better simulate request or job local state being reset between requests and prevent state leaking from one request to another.
To enable this, set
config.active_support.executor_around_test_case = true(this is the default in Rails 7).Alex Ghiculescu
-
Consider onion services secure for cookies.
Justin Tracey
-
Remove deprecated
Rails.config.action_view.raise_on_missing_translations.Rafael Mendonça França
-
Remove deprecated support to passing a path to
fixture_file_uploadrelative tofixture_path.Rafael Mendonça França
-
Remove deprecated
ActionDispatch::SystemTestCase#host!.Rafael Mendonça França
-
Remove deprecated
Rails.config.action_dispatch.hosts_response_app.Rafael Mendonça França
-
Remove deprecated
ActionDispatch::Response.return_only_media_type_on_content_type.Rafael Mendonça França
-
Raise
ActionController::Redirecting::UnsafeRedirectErrorfor unsaferedirect_toredirects.This allows
rescue_fromto be used to add a default fallback route:rescue_from ActionController::Redirecting::UnsafeRedirectError do redirect_to root_url endKasper Timm Hansen, Chris Oliver
-
Add
url_fromto verify a redirect location is internal.Takes the open redirect protection from
redirect_toso users can wrap a param, and fall back to an alternate redirect URL when the param provided one is unsafe.def create redirect_to url_from(params[:redirect_url]) || root_url enddmcge, Kasper Timm Hansen
-
Allow Capybara driver name overrides in
SystemTestCase::driven_byAllow users to prevent conflicts among drivers that use the same driver type (selenium, poltergeist, webkit, rack test).
Fixes #42502
Chris LaRose
-
Allow multiline to be passed in routes when using wildcard segments.
Previously routes with newlines weren't detected when using wildcard segments, returning a
No route matcheserror. After this change, routes with newlines are detected on wildcard segments. Exampledraw do get "/wildcard/*wildcard_segment", to: SimpleApp.new("foo#index"), as: :wildcard end # After the change, the path matches. assert_equal "/wildcard/a%0Anewline", url_helpers.wildcard_path(wildcard_segment: "a\nnewline")Fixes #39103
Ignacio Chiazzo
-
Treat html suffix in controller translation.
Rui Onodera, Gavin Miller
-
Allow permitting numeric params.
Previously it was impossible to permit different fields on numeric parameters. After this change you can specify different fields for each numbered parameter. For example params like,
book: { authors_attributes: { '0': { name: "William Shakespeare", age_of_death: "52" }, '1': { name: "Unattributed Assistant" }, '2': "Not a hash", 'new_record': { name: "Some name" } } }Before you could permit name on each author with,
permit book: { authors_attributes: [ :name ] }After this change you can permit different keys on each numbered element,
permit book: { authors_attributes: { '1': [ :name ], '0': [ :name, :age_of_death ] } }Fixes #41625
Adam Hess
-
Update
HostAuthorizationmiddleware to render debug info only whenconfig.consider_all_requests_localis set to true.Also, blocked host info is always logged with level
error.Fixes #42813
Nikita Vyrko
-
Add Server-Timing middleware
Server-Timing specification defines how the server can communicate to browsers performance metrics about the request it is responding to.
The ServerTiming middleware is enabled by default on
developmentenvironment by default using theconfig.server_timingsetting and set the relevant duration metrics in theServer-TimingheaderThe full specification for Server-Timing header can be found in: https://www.w3.org/TR/server-timing/#dfn-server-timing-header-field
Sebastian Sogamoso, Guillermo Iguaran
-
Use a static error message when raising
ActionDispatch::Http::Parameters::ParseErrorto avoid inadvertently logging the HTTP request body at thefatallevel when it contains malformed JSON.Fixes #41145
Aaron Lahey
-
Add
Middleware#delete!to delete middleware or raise if not found.Middleware#delete!works just likeMiddleware#deletebut will raise an error if the middleware isn't found.Alex Ghiculescu, Petrik de Heus, Junichi Sato
-
Raise error on unpermitted open redirects.
Add
allow_other_hostoptions toredirect_to. Opt in to this behaviour withActionController::Base.raise_on_open_redirects = true.Gannon McGibbon
-
Deprecate
poltergeistandwebkit(capybara-webkit) driver registration for system testing (they will be removed in Rails 7.1). Addcupriteinstead.Poltergeist and capybara-webkit are already not maintained. These usage in Rails are removed for avoiding confusing users.
Cuprite is a good alternative to Poltergeist. Some guide descriptions are replaced from Poltergeist to Cuprite.
Yusuke Iwaki
-
Exclude additional flash types from
ActionController::Base.action_methods.Ensures that additional flash types defined on ActionController::Base subclasses are not listed as actions on that controller.
class MyController < ApplicationController add_flash_types :hype end MyController.action_methods.include?('hype') # => falseGavin Morrice
-
OpenSSL constants are now used for Digest computations.
Dirkjan Bussink
-
Remove IE6-7-8 file download related hack/fix from ActionController::DataStreaming module.
Due to the age of those versions of IE this fix is no longer relevant, more importantly it creates an edge-case for unexpected Cache-Control headers.
Tadas Sasnauskas
-
Configuration setting to skip logging an uncaught exception backtrace when the exception is present in
rescued_responses.It may be too noisy to get all backtraces logged for applications that manage uncaught exceptions via
rescued_responsesandexceptions_app.config.action_dispatch.log_rescued_responses(defaults totrue) can be set tofalsein this case, so that only exceptions not found inrescued_responseswill be logged.Alexander Azarov, Mike Dalessio
-
Ignore file fixtures on
db:fixtures:load.Kevin Sjöberg
-
Fix ActionController::Live controller test deadlocks by removing the body buffer size limit for tests.
Dylan Thacker-Smith
-
New
ActionController::ConditionalGet#no_storemethod to set HTTP cache controlno-storedirective.Tadas Sasnauskas
-
Drop support for the
SERVER_ADDRheader.Following up https://github.com/rack/rack/pull/1573 and https://github.com/rails/rails/pull/42349.
Ricardo Díaz
-
Set session options when initializing a basic session.
Gannon McGibbon
-
Add
cache_control: {}option tofresh_whenandstale?.Works as a shortcut to set
response.cache_controlwith the above methods.Jacopo Beschi
-
Writing into a disabled session will now raise an error.
Previously when no session store was set, writing into the session would silently fail.
Jean Boussier
-
Add support for 'require-trusted-types-for' and 'trusted-types' headers.
Fixes #42034.
lfalcao
-
Remove inline styles and address basic accessibility issues on rescue templates.
Jacob Herrington
-
Add support for 'private, no-store' Cache-Control headers.
Previously, 'no-store' was exclusive; no other directives could be specified.
Alex Smith
-
Expand payload of
unpermitted_parameters.action_controllerinstrumentation to allow subscribers to know which controller action received unpermitted parameters.bbuchalter
-
Add
ActionController::Live#send_streamthat makes it more convenient to send generated streams:send_stream(filename: "subscribers.csv") do |stream| stream.writeln "email_address,updated_at" @subscribers.find_each do |subscriber| stream.writeln [ subscriber.email_address, subscriber.updated_at ].join(",") end endDHH
-
Add
ActionController::Live::Buffer#writelnto write a line to the stream with a newline included.DHH
-
ActionDispatch::Request#content_typenow returned Content-Type header as it is.Previously,
ActionDispatch::Request#content_typereturned value does NOT contain charset part. This behavior changed to returned Content-Type header containing charset part as it is.If you want just MIME type, please use
ActionDispatch::Request#media_typeinstead.Before:
request = ActionDispatch::Request.new("CONTENT_TYPE" => "text/csv; header=present; charset=utf-16", "REQUEST_METHOD" => "GET") request.content_type #=> "text/csv"After:
request = ActionDispatch::Request.new("Content-Type" => "text/csv; header=present; charset=utf-16", "REQUEST_METHOD" => "GET") request.content_type #=> "text/csv; header=present; charset=utf-16" request.media_type #=> "text/csv"Rafael Mendonça França
-
Change
ActionDispatch::Request#media_typeto returnnilwhen the request don't have aContent-Typeheader.Rafael Mendonça França
-
Fix error in
ActionController::LogSubscriberthat would happen when throwing inside a controller action.Janko Marohnić
-
Allow anything with
#to_str(likeAddressable::URI) as aredirect_tolocation.ojab
-
Change the request method to a
GETwhen passing failed requests down toconfig.exceptions_app.Alex Robbin
-
Deprecate the ability to assign a single value to
config.action_dispatch.trusted_proxiesasRemoteIpmiddleware behaves inconsistently depending on whether this is configured with a single value or an enumerable.Fixes #40772.
Christian Sutter
-
Add
redirect_back_or_to(fallback_location, **)as a more aesthetically pleasing version ofredirect_back fallback_location:, **. The old method name is retained without explicit deprecation.DHH
Action Text
-
Fix an issue with how nested lists were displayed when converting to plain text
Matt Swanson
-
Allow passing in a custom
direct_upload_urlorblob_url_templatetorich_text_area_tag.Lucas Mansur
-
Make the Action Text + Trix JavaScript and CSS available through the asset pipeline.
DHH
-
OpenSSL constants are now used for Digest computations.
Dirkjan Bussink
-
Add support for passing
form:option torich_text_area_tagandrich_text_areahelpers to specify the<input type="hidden" form="...">value.Sean Doyle
-
Add
config.action_text.attachment_tag_name, to specify the HTML tag that contains attachments.Mark VanLandingham
-
Expose how we render the HTML surrounding rich text content as an extensible
layouts/action_view/contents/_content.html.erbtemplate to encourage user-land customizations, while retaining private API control over how the rich text itself is rendered byaction_text/contents/_content.html.erbpartial.Sean Doyle
-
Add
with_all_rich_textmethod to eager load all rich text associations on a model at once.Matt Swanson, DHH
Action View
-
Support
include_hidden:option in calls toActionView::Helper::FormBuilder#file_fieldwithmultiple: trueto support submitting an empty collection of files.form.file_field :attachments, multiple: true # => <input type="hidden" autocomplete="off" name="post[attachments][]" value=""> <input type="file" multiple="multiple" id="post_attachments" name="post[attachments][]"> form.file_field :attachments, multiple: true, include_hidden: false # => <input type="file" multiple="multiple" id="post_attachments" name="post[attachments][]">Sean Doyle
-
Fix
number_with_precision(raise: true)always raising even on valid numbers.Pedro Moreira
-
Support
fields model: [@nested, @model]the same way asform_with model: [@nested, @model].Sean Doyle
-
Infer HTTP verb
[method]from a model or Array with model as the first argument tobutton_towhen combined with a block:button_to(Workshop.find(1)){ "Update" } #=> <form method="post" action="/workshops/1" class="button_to"> #=> <input type="hidden" name="_method" value="patch" autocomplete="off" /> #=> <button type="submit">Update</button> #=> </form> button_to([ Workshop.find(1), Session.find(1) ]) { "Update" } #=> <form method="post" action="/workshops/1/sessions/1" class="button_to"> #=> <input type="hidden" name="_method" value="patch" autocomplete="off" /> #=> <button type="submit">Update</button> #=> </form>Sean Doyle
-
Support passing a Symbol as the first argument to
FormBuilder#button:form.button(:draft, value: true) # => <button name="post[draft]" value="true" type="submit">Create post</button> form.button(:draft, value: true) do content_tag(:strong, "Save as draft") end # => <button name="post[draft]" value="true" type="submit"> # <strong>Save as draft</strong> # </button>Sean Doyle
-
Introduce the
field_nameview helper, along with theFormBuilder#field_namecounterpart:form_for @post do |f| f.field_tag :tag, name: f.field_name(:tag, multiple: true) # => <input type="text" name="post[tag][]"> endSean Doyle
-
Execute the
ActionView::Base.field_error_procwithin the context of theActionView::Baseinstance:config.action_view.field_error_proc = proc { |html| content_tag(:div, html, class: "field_with_errors") }Sean Doyle
-
Add support for
button_to ..., authenticity_token: falsebutton_to "Create", Post.new, authenticity_token: false # => <form class="button_to" method="post" action="/posts"><button type="submit">Create</button></form> button_to "Create", Post.new, authenticity_token: true # => <form class="button_to" method="post" action="/posts"><button type="submit">Create</button><input type="hidden" name="form_token" value="abc123..." autocomplete="off" /></form> button_to "Create", Post.new, authenticity_token: "secret" # => <form class="button_to" method="post" action="/posts"><button type="submit">Create</button><input type="hidden" name="form_token" value="secret" autocomplete="off" /></form>Sean Doyle
-
Support rendering
<form>elements without[action]attributes by:form_with url: falseorform_with ..., html: { action: false }form_for ..., url: falseorform_for ..., html: { action: false }form_tag falseorform_tag ..., action: falsebutton_to "...", falseorbutton_to(false) { ... }
Sean Doyle
-
Add
:day_formatoption todate_selectdate_select("article", "written_on", day_format: ->(day) { day.ordinalize }) # generates day options like <option value="1">1st</option>\n<option value="2">2nd</option>...Shunichi Ikegami
-
Allow
link_tohelper to infer link name fromModel#to_swhen it is used with a single argument:link_to @profile #=> <a href="/profiles/1">Eileen</a>This assumes the model class implements a
to_smethod like this:class Profile < ApplicationRecord # ... def to_s name end endPreviously you had to supply a second argument even if the
Profilemodel implemented a#to_smethod that called thenamemethod.link_to @profile, @profile.name #=> <a href="/profiles/1">Eileen</a>Olivier Lacan
-
Support svg unpaired tags for
taghelper.tag.svg { tag.use('href' => "#cool-icon") } # => <svg><use href="#cool-icon"></svg>Oleksii Vasyliev
-
Improves the performance of ActionView::Helpers::NumberHelper formatters by avoiding the use of exceptions as flow control.
Mike Dalessio
-
preload_link_tagproperly insertsasattributes for files withimageMIME types, such as JPG or SVG.Nate Berkopec
-
Add
weekday_options_for_selectandweekday_selecthelper methods. Also addsweekday_selecttoFormBuilder.Drew Bragg, Dana Kashubeck, Kasper Timm Hansen
-
Add
caching?helper that returns whether the current code path is being cached anduncacheable!to denote helper methods that can't participate in fragment caching.Ben Toews, John Hawthorn, Kasper Timm Hansen, Joel Hawksley
-
Add
include_secondsoption fortime_field.<%= form.time_field :foo, include_seconds: false %> # => <input value="16:22" type="time" />Default includes seconds:
<%= form.time_field :foo %> # => <input value="16:22:01.440" type="time" />This allows you to take advantage of different rendering options in some browsers.
Alex Ghiculescu
-
Improve error messages when template file does not exist at absolute filepath.
Ted Whang
-
Add
:country_codeoption tosms_tofor consistency withphone_to.Jonathan Hefner
-
OpenSSL constants are now used for Digest computations.
Dirkjan Bussink
-
The
translatehelper now passesdefaultvalues that aren't translation keys throughI18n.translatefor interpolation.Jonathan Hefner
-
Adds option
extnametostylesheet_link_tagto skip default.cssextension appended to the stylesheet path.Before:
stylesheet_link_tag "style.less" # <link href="/stylesheets/style.less.scss" rel="stylesheet">After:
stylesheet_link_tag "style.less", extname: false, skip_pipeline: true, rel: "stylesheet/less" # <link href="/stylesheets/style.less" rel="stylesheet/less">Abhay Nikam
-
Deprecate
renderlocals to be assigned to instance variables.Petrik de Heus
-
Remove legacy default
media=screenfromstylesheet_link_tag.André Luis Leal Cardoso Junior
-
Change
ActionView::Helpers::FormBuilder#buttonto transformformmethodattributes into_method="$VERB"Form Data to enable varied same-form actions:<%= form_with model: post, method: :put do %> <%= form.button "Update" %> <%= form.button "Delete", formmethod: :delete %> <% end %> <%# => <form action="posts/1"> => <input type="hidden" name="_method" value="put"> => <button type="submit">Update</button> => <button type="submit" formmethod="post" name="_method" value="delete">Delete</button> => </form> %>Sean Doyle
-
Change
ActionView::Helpers::UrlHelper#button_toto always render a<button>element, regardless of whether or not the content is passed as the first argument or as a block.<%= button_to "Delete", post_path(@post), method: :delete %> # => <form action="/posts/1"><input type="hidden" name="_method" value="delete"><button type="submit">Delete</button></form> <%= button_to post_path(@post), method: :delete do %> Delete <% end %> # => <form action="/posts/1"><input type="hidden" name="_method" value="delete"><button type="submit">Delete</button></form>Sean Doyle, Dusan Orlovic
-
Add
config.action_view.preload_links_headerto allow disabling of theLinkheader being added by default when usingstylesheet_link_tagandjavascript_include_tag.Andrew White
-
The
translatehelper now resolvesdefaultvalues when anilkey is specified, instead of always returningnil.Jonathan Hefner
-
Add
config.action_view.image_loadingto configure the default value of theimage_tag:loadingoption.By setting
config.action_view.image_loading = "lazy", an application can opt in to lazy loading images sitewide, without changing view code.Jonathan Hefner
-
ActionView::Helpers::FormBuilder#idreturns the value of the<form>element'sidattribute. With amethodargument, returns theidattribute for a form field with that name.<%= form_for @post do |f| %> <%# ... %> <% content_for :sticky_footer do %> <%= form.button(form: f.id) %> <% end %> <% end %>Sean Doyle
-
ActionView::Helpers::FormBuilder#field_idreturns the value generated by the FormBuilder for the given attribute name.<%= form_for @post do |f| %> <%= f.label :title %> <%= f.text_field :title, aria: { describedby: f.field_id(:title, :error) } %> <%= tag.span("is blank", id: f.field_id(:title, :error) %> <% end %>Sean Doyle
-
Add
tag.attributesto transform a Hash into HTML Attributes, ready to be interpolated into ERB.<input <%= tag.attributes(type: :text, aria: { label: "Search" }) %> > # => <input type="text" aria-label="Search">Sean Doyle
Active Job
-
Remove deprecated
:return_false_on_aborted_enqueueoption.Rafael Mendonça França
-
Deprecated
Rails.config.active_job.skip_after_callbacks_if_terminated.Rafael Mendonça França
-
Removed deprecated behavior that was not halting
after_enqueue/after_performcallbacks when a previous callback was halted withthrow :abort.Rafael Mendonça França
-
Raise an
SerializationErrorinSerializer::ModuleSerializerif the module name is not present.Veerpal Brar
-
Allow a job to retry indefinitely
The
attemptsparameter of theretry_onmethod now accepts the symbol reference:unlimitedin addition to a specific number of retry attempts to allow a developer to specify that a job should retry forever until it succeeds.class MyJob < ActiveJob::Base retry_on(AlwaysRetryException, attempts: :unlimited) # the actual job code endDaniel Morton
-
Added possibility to check on
:priorityin test helper methodsassert_enqueued_withandassert_performed_with.Wojciech Wnętrzak
-
OpenSSL constants are now used for Digest computations.
Dirkjan Bussink
-
Add a Serializer for the Range class.
This should allow things like
MyJob.perform_later(range: 1..100). -
Communicate enqueue failures to callers of
perform_later.perform_latercan now optionally take a block which will execute after the adapter attempts to enqueue the job. The block will receive the job instance as an argument even if the enqueue was not successful. Additionally,ActiveJobadapters now have the ability to raise anActiveJob::EnqueueErrorwhich will be caught and stored in the job instance so code attempting to enqueue jobs can inspect any raisedEnqueueErrorusing the block.MyJob.perform_later do |job| unless job.successfully_enqueued? if job.enqueue_error&.message == "Redis was unavailable" # invoke some code that will retry the job after a delay end end endDaniel Morton
-
Don't log rescuable exceptions defined with
rescue_from.Hu Hailin
-
Allow
rescue_fromto rescue all exceptions.Adrianna Chang, Étienne Barrié
Active Model
-
Remove support to Marshal load Rails 5.x
ActiveModel::AttributeSetformat.Rafael Mendonça França
-
Remove support to Marshal and YAML load Rails 5.x error format.
Rafael Mendonça França
-
Remove deprecated support to use
[]=inActiveModel::Errors#messages.Rafael Mendonça França
-
Remove deprecated support to
deleteerrors fromActiveModel::Errors#messages.Rafael Mendonça França
-
Remove deprecated support to
clearerrors fromActiveModel::Errors#messages.Rafael Mendonça França
-
Remove deprecated support concat errors to
ActiveModel::Errors#messages.Rafael Mendonça França
-
Remove deprecated
ActiveModel::Errors#to_xml.Rafael Mendonça França
-
Remove deprecated
ActiveModel::Errors#keys.Rafael Mendonça França
-
Remove deprecated
ActiveModel::Errors#values.Rafael Mendonça França
-
Remove deprecated
ActiveModel::Errors#slice!.Rafael Mendonça França
-
Remove deprecated
ActiveModel::Errors#to_h.Rafael Mendonça França
-
Remove deprecated enumeration of
ActiveModel::Errorsinstances as a Hash.Rafael Mendonça França
-
Clear secure password cache if password is set to
nilBefore:
user.password = 'something' user.password = nil
user.password # => 'something'
Now:
user.password = 'something' user.password = nil
user.password # => nil
Markus Doits
-
Introduce
ActiveModel::API.Make
ActiveModel::APIthe minimum API to talk with Action Pack and Action View. This will allow adding more functionality toActiveModel::Model.Petrik de Heus, Nathaniel Watts
-
Fix dirty check for Float::NaN and BigDecimal::NaN.
Float::NaN and BigDecimal::NaN in Ruby are special values and can't be compared with
==.Marcelo Lauxen
-
Fix
to_jsonforActiveModel::Dirtyobject.Exclude
mutations_from_databaseattribute from json as it lead to recursion.Anil Maurya
-
Add
ActiveModel::AttributeSet#values_for_database.Returns attributes with values for assignment to the database.
Chris Salzberg
-
Fix delegation in ActiveModel::Type::Registry#lookup and ActiveModel::Type.lookup.
Passing a last positional argument
{}would be incorrectly considered as keyword argument.Benoit Daloze
-
Cache and re-use generated attribute methods.
Generated methods with identical implementations will now share their instruction sequences leading to reduced memory retention, and slightly faster load time.
Jean Boussier
-
Add
in: rangeparameter tonumericalityvalidator.Michal Papis
-
Add
localeargument toActiveModel::Name#initializeto be used to generate thesingular,plural,route_keyandsingular_route_keyvalues.Lukas Pokorny
-
Make ActiveModel::Errors#inspect slimmer for readability
lulalala
Active Record
-
Better handle SQL queries with invalid encoding.
Post.create(name: "broken \xC8 UTF-8")Would cause all adapters to fail in a non controlled way in the code responsible to detect write queries.
The query is now properly passed to the database connection, which might or might not be able to handle it, but will either succeed or failed in a more correct way.
Jean Boussier
-
Move database and shard selection config options to a generator.
Rather than generating the config options in
production.rbwhen applications are created, applications can now run a generator to create an initializer and uncomment / update options as needed. All multi-db configuration can be implemented in this initializer.Eileen M. Uchitelle
-
Remove deprecated
ActiveRecord::DatabaseConfigurations::DatabaseConfig#spec_name.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Connection#in_clause_length.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Connection#allowed_index_name_length.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base#remove_connection.Rafael Mendonça França
-
Load STI Models in fixtures
Data from Fixtures now loads based on the specific class for models with Single Table Inheritance. This affects enums defined in subclasses, previously the value of these fields was not parsed and remained
nilAndres Howard
-
#authenticatereturns false when the password is blank instead of raising an error.Muhammad Muhammad Ibrahim
-
Fix
ActiveRecord::QueryMethods#in_order_ofbehavior for integer enums.ActiveRecord::QueryMethods#in_order_ofdidn't work as expected for enums stored as integers in the database when passing an array of strings or symbols as the order argument. This unexpected behavior occurred because the string or symbol values were not casted to match the integers in the database.The following example now works as expected:
class Book < ApplicationRecord enum status: [:proposed, :written, :published] end Book.in_order_of(:status, %w[written published proposed])Alexandre Ruban
-
Ignore persisted in-memory records when merging target lists.
Kevin Sjöberg
-
Add a new option
:update_onlytoupsert_allto configure the list of columns to update in case of conflict.Before, you could only customize the update SQL sentence via
:on_duplicate. There is now a new option:update_onlythat lets you provide a list of columns to update in case of conflict:Commodity.upsert_all( [ { id: 2, name: "Copper", price: 4.84 }, { id: 4, name: "Gold", price: 1380.87 }, { id: 6, name: "Aluminium", price: 0.35 } ], update_only: [:price] # Only prices will be updated )Jorge Manrubia
-
Remove deprecated
ActiveRecord::Result#map!andActiveRecord::Result#collect!.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base.configurations.to_h.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base.configurations.default_hash.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base.arel_attribute.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base.connection_config.Rafael Mendonça França
-
Filter attributes in SQL logs
Previously, SQL queries in logs containing
ActiveRecord::Base.filter_attributeswere not filtered.Now, the filter attributes will be masked
[FILTERED]in the logs whenprepared_statementis enabled.# Before: Foo Load (0.2ms) SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ? [["passw", "hello"], ["LIMIT", 1]] # After: Foo Load (0.5ms) SELECT "foos".* FROM "foos" WHERE "foos"."passw" = ? LIMIT ? [["passw", "[FILTERED]"], ["LIMIT", 1]]Aishwarya Subramanian
-
Remove deprecated
Tasks::DatabaseTasks.spec.Rafael Mendonça França
-
Remove deprecated
Tasks::DatabaseTasks.current_config.Rafael Mendonça França
-
Deprecate
Tasks::DatabaseTasks.schema_file_type.Rafael Mendonça França
-
Remove deprecated
Tasks::DatabaseTasks.dump_filename.Rafael Mendonça França
-
Remove deprecated
Tasks::DatabaseTasks.schema_file.Rafael Mendonça França
-
Remove deprecated
environmentandnamearguments fromTasks::DatabaseTasks.schema_up_to_date?.Rafael Mendonça França
-
Merging conditions on the same column no longer maintain both conditions, and will be consistently replaced by the latter condition.
# Rails 6.1 (IN clause is replaced by merger side equality condition) Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob] # Rails 6.1 (both conflict conditions exists, deprecated) Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [] # Rails 6.1 with rewhere to migrate to Rails 7.0's behavior Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob] # Rails 7.0 (same behavior with IN clause, mergee side condition is consistently replaced) Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob] Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob] *Rafael Mendonça França* -
Remove deprecated support to
Model.reorder(nil).firstto search using non-deterministic order.Rafael Mendonça França
-
Remove deprecated rake tasks:
db:schema:load_if_rubydb:structure:dumpdb:structure:loaddb:structure:load_if_sqldb:structure:dump:#{name}db:structure:load:#{name}db:test:load_structuredb:test:load_structure:#{name}
Rafael Mendonça França
-
Remove deprecated
DatabaseConfig#configmethod.Rafael Mendonça França
-
Rollback transactions when the block returns earlier than expected.
Before this change, when a transaction block returned early, the transaction would be committed.
The problem is that timeouts triggered inside the transaction block was also making the incomplete transaction to be committed, so in order to avoid this mistake, the transaction block is rolled back.
Rafael Mendonça França
-
Add middleware for automatic shard swapping.
Provides a basic middleware to perform automatic shard swapping. Applications will provide a resolver which will determine for an individual request which shard should be used. Example:
config.active_record.shard_resolver = ->(request) { subdomain = request.subdomain tenant = Tenant.find_by_subdomain!(subdomain) tenant.shard }See guides for more details.
Eileen M. Uchitelle, John Crepezzi
-
Remove deprecated support to pass a column to
type_cast.Rafael Mendonça França
-
Remove deprecated support to type cast to database values
ActiveRecord::Baseobjects.Rafael Mendonça França
-
Remove deprecated support to quote
ActiveRecord::Baseobjects.Rafael Mendonça França
-
Remove deprecacated support to resolve connection using
"primary"as connection specification name.Rafael Mendonça França
-
Remove deprecation warning when using
:intervalcolumn is used in PostgreSQL database.Now, interval columns will return
ActiveSupport::Durationobjects instead of strings.To keep the old behavior, you can add this line to your model:
attribute :column, :stringRafael Mendonça França
-
Remove deprecated support to YAML load
ActiveRecord::Baseinstance in the Rails 4.2 and 4.1 formats.Rafael Mendonça França
-
Remove deprecated option
:spec_namein theconfigs_formethod.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base.allow_unsafe_raw_sql.Rafael Mendonça França
-
Fix regression bug that caused ignoring additional conditions for preloading has_many-through relations.
Fixes #43132
Alexander Pauly
-
Fix
has_manyinversing recursion on models with recursive associations.Gannon McGibbon
-
Add
accepts_nested_attributes_forsupport fordelegated_typeclass Entry < ApplicationRecord delegated_type :entryable, types: %w[ Message Comment ] accepts_nested_attributes_for :entryable end entry = Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' }) # => #<Entry:0x00> # id: 1 # entryable_id: 1, # entryable_type: 'Message' # ...> entry.entryable # => #<Message:0x01> # id: 1 # content: 'Hello world' # ...>Previously it would raise an error:
Entry.create(entryable_type: 'Message', entryable_attributes: { content: 'Hello world' }) # ArgumentError: Cannot build association `entryable'. Are you trying to build a polymorphic one-to-one association?Sjors Baltus
-
Use subquery for DELETE with GROUP_BY and HAVING clauses.
Prior to this change, deletes with GROUP_BY and HAVING were returning an error.
After this change, GROUP_BY and HAVING are valid clauses in DELETE queries, generating the following query:
DELETE FROM "posts" WHERE "posts"."id" IN ( SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" GROUP BY "posts"."id" HAVING (count(comments.id) >= 2)) ) [["flagged", "t"]]Ignacio Chiazzo Cardarello
-
Use subquery for UPDATE with GROUP_BY and HAVING clauses.
Prior to this change, updates with GROUP_BY and HAVING were being ignored, generating a SQL like this:
UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN ( SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" ) [["flagged", "t"]]After this change, GROUP_BY and HAVING clauses are used as a subquery in updates, like this:
UPDATE "posts" SET "flagged" = ? WHERE "posts"."id" IN ( SELECT "posts"."id" FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" GROUP BY posts.id HAVING (count(comments.id) >= 2) ) [["flagged", "t"]]Ignacio Chiazzo Cardarello
-
Add support for setting the filename of the schema or structure dump in the database config.
Applications may now set their the filename or path of the schema / structure dump file in their database configuration.
production: primary: database: my_db schema_dump: my_schema_dump_filename.rb animals: database: animals_db schema_dump: falseThe filename set in
schema_dumpwill be used by the application. If set tofalsethe schema will not be dumped. The database tasks are responsible for adding the database directory to the filename. If a full path is provided, the Rails tasks will use that instead ofActiveRecord::DatabaseTasks.db_dir.Eileen M. Uchitelle, Ryan Kerr
-
Add
ActiveRecord::Base.prohibit_shard_swappingto prevent attempts to change the shard within a block.John Crepezzi, Eileen M. Uchitelle
-
Filter unchanged attributes with default function from insert query when
partial_insertsis disabled.Akshay Birajdar, Jacopo Beschi
-
Add support for FILTER clause (SQL:2003) to Arel.
Currently supported by PostgreSQL 9.4+ and SQLite 3.30+.
Andrey Novikov
-
Automatically set timestamps on record creation during bulk insert/upsert
Prior to this change, only updates during an upsert operation (e.g.
upsert_all) would touch timestamps (updated_{at,on}). Now, record creations also touch timestamp columns ({created,updated}_{at,on}).This behaviour is controlled by the
<model>.record_timestampsconfig, matching the behaviour ofcreate,update, etc. It can also be overridden by using therecord_timestamps:keyword argument.Note that this means
upsert_allon models withrecord_timestamps = falsewill no longer touchupdated_{at,on}automatically.Sam Bostock
-
Don't require
rolewhen passingshardtoconnected_to.connected_tocan now be called with ashardonly. Note thatroleis still inherited ifconnected_tocalls are nested.Eileen M. Uchitelle
-
Add option to lazily load the schema cache on the connection.
Previously, the only way to load the schema cache in Active Record was through the Railtie on boot. This option provides the ability to load the schema cache on the connection after it's been established. Loading the cache lazily on the connection can be beneficial for Rails applications that use multiple databases because it will load the cache at the time the connection is established. Currently Railties doesn't have access to the connections before boot.
To use the cache, set
config.active_record.lazily_load_schema_cache = truein your application configuration. In addition aschema_cache_pathshould be set in your database configuration if you don't want to use the default "db/schema_cache.yml" path.Eileen M. Uchitelle
-
Allow automatic
inverse_ofdetection for associations with scopes.Automatic
inverse_ofdetection now works for associations with scopes. For example, thecommentsassociation here now automatically detectsinverse_of: :post, so we don't need to pass that option:class Post < ActiveRecord::Base has_many :comments, -> { visible } end class Comment < ActiveRecord::Base belongs_to :post endNote that the automatic detection still won't work if the inverse association has a scope. In this example a scope on the
postassociation would still prevent Rails from finding the inverse for thecommentsassociation.This will be the default for new apps in Rails 7. To opt in:
config.active_record.automatic_scope_inversing = trueDaniel Colson, Chris Bloom
-
Accept optional transaction args to
ActiveRecord::Locking::Pessimistic#with_lock#with_locknow accepts transaction options likerequires_new:,isolation:, andjoinable:John Mileham
-
Adds support for deferrable foreign key constraints in PostgreSQL.
By default, foreign key constraints in PostgreSQL are checked after each statement. This works for most use cases, but becomes a major limitation when creating related records before the parent record is inserted into the database. One example of this is looking up / creating a person via one or more unique alias.
Person.transaction do alias = Alias .create_with(user_id: SecureRandom.uuid) .create_or_find_by(name: "DHH") person = Person .create_with(name: "David Heinemeier Hansson") .create_or_find_by(id: alias.user_id) endUsing the default behavior, the transaction would fail when executing the first
INSERTstatement.By passing the
:deferrableoption to theadd_foreign_keystatement in migrations, it's possible to defer this check.add_foreign_key :aliases, :person, deferrable: truePassing
deferrable: truedoesn't change the default behavior, but allows manually deferring the check usingSET CONSTRAINTS ALL DEFERREDwithin a transaction. This will cause the foreign keys to be checked after the transaction.It's also possible to adjust the default behavior from an immediate check (after the statement), to a deferred check (after the transaction):
add_foreign_key :aliases, :person, deferrable: :deferredBenedikt Deicke
-
Allow configuring Postgres password through the socket URL.
For example:
ActiveRecord::DatabaseConfigurations::UrlConfig.new( :production, :production, 'postgres:///?user=user&password=secret&dbname=app', {} ).configuration_hashwill now return,
{ :user=>"user", :password=>"secret", :dbname=>"app", :adapter=>"postgresql" }Abeid Ahmed
-
PostgreSQL: support custom enum types
In migrations, use
create_enumto add a new enum type, andt.enumto add a column.def up create_enum :mood, ["happy", "sad"] change_table :cats do |t| t.enum :current_mood, enum_type: "mood", default: "happy", null: false end endEnums will be presented correctly in
schema.rb. Note that this is only supported by the PostgreSQL adapter.Alex Ghiculescu
-
Avoid COMMENT statements in PostgreSQL structure dumps
COMMENT statements are now omitted from the output of
db:structure:dumpwhen using PostgreSQL >= 11. This allows loading the dump without a pgsql superuser account.Fixes #36816, #43107.
Janosch Müller
-
Add support for generated columns in PostgreSQL adapter
Generated columns are supported since version 12.0 of PostgreSQL. This adds support of those to the PostgreSQL adapter.
create_table :users do |t| t.string :name t.virtual :name_upcased, type: :string, as: 'upper(name)', stored: true endMichał Begejowicz
-
Remove warning when overwriting existing scopes
Removes the following unnecessary warning message that appeared when overwriting existing scopes
Creating scope :my_scope_name. Overwriting existing method "MyClass.my_scope_name" when overwriting existing scopesWeston Ganger
-
Use full precision for
updated_atininsert_all/upsert_allCURRENT_TIMESTAMPprovides differing precision depending on the database, and not all databases support explicitly specifying additional precision.Instead, we delegate to the new
connection.high_precision_current_timestampfor the SQL to produce a high precision timestamp on the current database.Fixes #42992
Sam Bostock
-
Add ssl support for postgresql database tasks
Add
PGSSLMODE,PGSSLCERT,PGSSLKEYandPGSSLROOTCERTto pg_env from database config when running postgresql database tasks.# config/database.yml production: sslmode: verify-full sslcert: client.crt sslkey: client.key sslrootcert: ca.crtEnvironment variables
PGSSLMODE=verify-full PGSSLCERT=client.crt PGSSLKEY=client.key PGSSLROOTCERT=ca.crtFixes #42994
Michael Bayucot
-
Avoid scoping update callbacks in
ActiveRecord::Relation#update!.Making it consistent with how scoping is applied only to the query in
ActiveRecord::Relation#updateand not also to the callbacks from the update itself.Dylan Thacker-Smith
-
Fix 2 cases that inferred polymorphic class from the association's
foreign_typeusingString#constantizeinstead of the model'spolymorphic_class_for.When updating a polymorphic association, the old
foreign_typewas not inferred correctly when:touching the previously associated record- updating the previously associated record's
counter_cache
Jimmy Bourassa
-
Add config option for ignoring tables when dumping the schema cache.
Applications can now be configured to ignore certain tables when dumping the schema cache.
The configuration option can table an array of tables:
config.active_record.schema_cache_ignored_tables = ["ignored_table", "another_ignored_table"]Or a regex:
config.active_record.schema_cache_ignored_tables = [/^_/]Eileen M. Uchitelle
-
Make schema cache methods return consistent results.
Previously the schema cache methods
primary_keys,columns,columns_hash, andindexeswould behave differently than one another when a table didn't exist and differently across database adapters. This change unifies the behavior so each method behaves the same regardless of adapter.The behavior now is:
columns: (unchanged) raises a db error if the table does not exist.columns_hash: (unchanged) raises a db error if the table does not exist.primary_keys: (unchanged) returnsnilif the table does not exist.indexes: (changed for mysql2) returns[]if the table does not exist.Eileen M. Uchitelle
-
Reestablish connection to previous database after after running
db:schema:load:nameAfter running
db:schema:load:namethe previous connection is restored.Jacopo Beschi
-
Add database config option
database_tasksIf you would like to connect to an external database without any database management tasks such as schema management, migrations, seeds, etc. you can set the per database config option
database_tasks: false# config/database.yml production: primary: database: my_database adapter: mysql2 animals: database: my_animals_database adapter: mysql2 database_tasks: falseWeston Ganger
-
Fix
ActiveRecord::InternalMetadatato not be broken byconfig.active_record.record_timestamps = falseSince the model always create the timestamp columns, it has to set them, otherwise it breaks various DB management tasks.
Fixes #42983
-
Add
ActiveRecord::QueryLogs.Configurable tags can be automatically added to all SQL queries generated by Active Record.
# config/application.rb module MyApp class Application < Rails::Application config.active_record.query_log_tags_enabled = true end endBy default the application, controller and action details are added to the query tags:
class BooksController < ApplicationController def index @books = Book.all end endGET /books # SELECT * FROM books /*application:MyApp;controller:books;action:index*/Custom tags containing static values and Procs can be defined in the application configuration:
config.active_record.query_log_tags = [ :application, :controller, :action, { custom_static: "foo", custom_dynamic: -> { Time.now } } ]Keeran Raj Hawoldar, Eileen M. Uchitelle, Kasper Timm Hansen
-
Added support for multiple databases to
rails db:setupandrails db:reset.Ryan Hall
-
Add
ActiveRecord::Relation#structurally_compatible?.Adds a query method by which a user can tell if the relation that they're about to use for
#oror#andis structurally compatible with the receiver.Kevin Newton
-
Add
ActiveRecord::QueryMethods#in_order_of.This allows you to specify an explicit order that you'd like records returned in based on a SQL expression. By default, this will be accomplished using a case statement, as in:
Post.in_order_of(:id, [3, 5, 1])will generate the SQL:
SELECT "posts".* FROM "posts" ORDER BY CASE "posts"."id" WHEN 3 THEN 1 WHEN 5 THEN 2 WHEN 1 THEN 3 ELSE 4 END ASCHowever, because this functionality is built into MySQL in the form of the
FIELDfunction, that connection adapter will generate the following SQL instead:SELECT "posts".* FROM "posts" ORDER BY FIELD("posts"."id", 1, 5, 3) DESCKevin Newton
-
Fix
eager_loading?when ordering withSymbol.eager_loading?is triggered correctly when usingorderwith symbols.scope = Post.includes(:comments).order(:"comments.label") => trueJacopo Beschi
-
Two change tracking methods are added for
belongs_toassociations.The
association_changed?method (assuming an association named:association) returns true if a different associated object has been assigned and the foreign key will be updated in the next save.The
association_previously_changed?method returns true if the previous save updated the association to reference a different associated object.George Claghorn
-
Add option to disable schema dump per-database.
Dumping the schema is on by default for all databases in an application. To turn it off for a specific database, use the
schema_dumpoption:# config/database.yml production: schema_dump: falseLuis Vasconcellos, Eileen M. Uchitelle
-
Fix
eager_loading?when ordering withHashsyntax.eager_loading?is triggered correctly when usingorderwith hash syntax on an outer table.Post.includes(:comments).order({ "comments.label": :ASC }).eager_loading? # => trueJacopo Beschi
-
Move the forcing of clear text encoding to the
ActiveRecord::Encryption::Encryptor.Fixes #42699.
J Smith
-
partial_insertsis now disabled by default in new apps.This will be the default for new apps in Rails 7. To opt in:
config.active_record.partial_inserts = trueIf a migration removes the default value of a column, this option would cause old processes to no longer be able to create new records.
If you need to remove a column, you should first use
ignored_columnsto stop using it.Jean Boussier
-
Rails can now verify foreign keys after loading fixtures in tests.
This will be the default for new apps in Rails 7. To opt in:
config.active_record.verify_foreign_keys_for_fixtures = trueTests will not run if there is a foreign key constraint violation in your fixture data.
The feature is supported by SQLite and PostgreSQL, other adapters can also add support for it.
Alex Ghiculescu
-
Clear cached
has_oneassociation after settingbelongs_toassociation tonil.After setting a
belongs_torelation toniland updating an unrelated attribute on the owner, the owner should still returnnilon thehas_onerelation.Fixes #42597.
Michiel de Mare
-
OpenSSL constants are now used for Digest computations.
Dirkjan Bussink
-
Adds support for
if_not_existstoadd_foreign_keyandif_existstoremove_foreign_key.Applications can set their migrations to ignore exceptions raised when adding a foreign key that already exists or when removing a foreign key that does not exist.
Example Usage:
class AddAuthorsForeignKeyToArticles < ActiveRecord::Migration[7.0] def change add_foreign_key :articles, :authors, if_not_exists: true end endclass RemoveAuthorsForeignKeyFromArticles < ActiveRecord::Migration[7.0] def change remove_foreign_key :articles, :authors, if_exists: true end endRoberto Miranda
-
Prevent polluting ENV during postgresql structure dump/load.
Some configuration parameters were provided to pg_dump / psql via environment variables which persisted beyond the command being run, and may have caused subsequent commands and connections to fail. Tasks running across multiple postgresql databases like
rails db:test:preparemay have been affected.Samuel Cochran
-
Set precision 6 by default for
datetimecolumns.By default, datetime columns will have microseconds precision instead of seconds precision.
Roberto Miranda
-
Allow preloading of associations with instance dependent scopes.
John Hawthorn, John Crepezzi, Adam Hess, Eileen M. Uchitelle, Dinah Shi
-
Do not try to rollback transactions that failed due to a
ActiveRecord::TransactionRollbackError.Jamie McCarthy
-
Active Record Encryption will now encode values as UTF-8 when using deterministic encryption. The encoding is part of the encrypted payload, so different encodings for different values result in different ciphertexts. This can break unique constraints and queries.
The new behavior is configurable via
active_record.encryption.forced_encoding_for_deterministic_encryptionthat isEncoding::UTF_8by default. It can be disabled by setting it tonil.Jorge Manrubia
-
The MySQL adapter now cast numbers and booleans bind parameters to string for safety reasons.
When comparing a string and a number in a query, MySQL converts the string to a number. So for instance
"foo" = 0, will implicitly cast"foo"to0and will evaluate toTRUEwhich can lead to security vulnerabilities.Active Record already protect against that vulnerability when it knows the type of the column being compared, however until now it was still vulnerable when using bind parameters:
User.where("login_token = ?", 0).firstWould perform:
SELECT * FROM `users` WHERE `login_token` = 0 LIMIT 1;Now it will perform:
SELECT * FROM `users` WHERE `login_token` = '0' LIMIT 1;Jean Boussier
-
Fixture configurations (
_fixture) are now strictly validated.If an error will be raised if that entry contains unknown keys while previously it would silently have no effects.
Jean Boussier
-
Add
ActiveRecord::Base.update!that works likeActiveRecord::Base.updatebut raises exceptions.This allows for the same behavior as the instance method
#update!at a class level.Person.update!(:all, state: "confirmed")Dorian Marié
-
Add
ActiveRecord::Base#attributes_for_database.Returns attributes with values for assignment to the database.
Chris Salzberg
-
Use an empty query to check if the PostgreSQL connection is still active.
An empty query is faster than
SELECT 1.Heinrich Lee Yu
-
Add
ActiveRecord::Base#previously_persisted?.Returns
trueif the object has been previously persisted but now it has been deleted. -
Deprecate
partial_writesin favor ofpartial_insertsandpartial_updates.This allows to have a different behavior on update and create.
Jean Boussier
-
Fix compatibility with
psych >= 4.Starting in Psych 4.0.0
YAML.loadbehaves likeYAML.safe_load. To preserve compatibility, Active Record's schema cache loader andYAMLColumnnow usesYAML.unsafe_loadif available.Jean Boussier
-
ActiveRecord::Base.loggeris now aclass_attribute.This means it can no longer be accessed directly through
@@logger, and that settinglogger =on a subclass won't change the parent's logger.Jean Boussier
-
Add
.asc.nulls_firstfor all databases. Unfortunately MySQL still doesn't likenulls_last.Keenan Brock
-
Improve performance of
one?andmany?by limiting the generated count query to 2 results.Gonzalo Riestra
-
Don't check type when using
if_not_existsonadd_column.Previously, if a migration called
add_columnwith theif_not_existsoption set to true thecolumn_exists?check would look for a column with the same name and type as the migration.Recently it was discovered that the type passed to the migration is not always the same type as the column after migration. For example a column set to
:mediumblobin the migration will be casted tobinarywhen callingcolumn.type. Since there is no straightforward way to cast the type to the database type without running the migration, we opted to drop the type check fromadd_column. This means that migrations adding a duplicate column with a different type will no longer raise an error.Eileen M. Uchitelle
-
Log a warning message when running SQLite in production.
Using SQLite in production ENV is generally discouraged. SQLite is also the default adapter in a new Rails application. For the above reasons log a warning message when running SQLite in production.
The warning can be disabled by setting
config.active_record.sqlite3_production_warning=false.Jacopo Beschi
-
Add option to disable joins for
has_oneassociations.In a multiple database application, associations can't join across databases. When set, this option instructs Rails to generate 2 or more queries rather than generating joins for
has_oneassociations.Set the option on a has one through association:
class Person has_one :dog has_one :veterinarian, through: :dog, disable_joins: true endThen instead of generating join SQL, two queries are used for
@person.veterinarian:SELECT "dogs"."id" FROM "dogs" WHERE "dogs"."person_id" = ? [["person_id", 1]] SELECT "veterinarians".* FROM "veterinarians" WHERE "veterinarians"."dog_id" = ? [["dog_id", 1]]Sarah Vessels, Eileen M. Uchitelle
-
Arel::Visitors::Dotnow renders a complete set of properties when visitingArel::Nodes::SelectCore,SelectStatement,InsertStatement,UpdateStatement, andDeleteStatement, which fixes #42026. Previously, some properties were omitted.Mike Dalessio
-
Arel::Visitors::Dotnow supportsArel::Nodes::Bin,Case,CurrentRow,Distinct,DistinctOn,Else,Except,InfixOperation,Intersect,Lock,NotRegexp,Quoted,Regexp,UnaryOperation,Union,UnionAll,When, andWith. Previously, these node types caused an exception to be raised byArel::Visitors::Dot#accept.Mike Dalessio
-
Optimize
remove_columnsto use a single SQL statement.remove_columns :my_table, :col_one, :col_twoNow results in the following SQL:
ALTER TABLE "my_table" DROP COLUMN "col_one", DROP COLUMN "col_two"Jon Dufresne
-
Ensure
has_oneautosave association callbacks get called once.Change the
has_oneautosave callback to be non cyclic as well. By doing this the autosave callback are made more consistent for all 3 cases:has_many,has_one, andbelongs_to.Petrik de Heus
-
Add option to disable joins for associations.
In a multiple database application, associations can't join across databases. When set, this option instructs Rails to generate 2 or more queries rather than generating joins for associations.
Set the option on a has many through association:
class Dog has_many :treats, through: :humans, disable_joins: true has_many :humans endThen instead of generating join SQL, two queries are used for
@dog.treats:SELECT "humans"."id" FROM "humans" WHERE "humans"."dog_id" = ? [["dog_id", 1]] SELECT "treats".* FROM "treats" WHERE "treats"."human_id" IN (?, ?, ?) [["human_id", 1], ["human_id", 2], ["human_id", 3]]Eileen M. Uchitelle, Aaron Patterson, Lee Quarella
-
Add setting for enumerating column names in SELECT statements.
Adding a column to a PostgreSQL database, for example, while the application is running can change the result of wildcard
SELECT *queries, which invalidates the result of cached prepared statements and raises aPreparedStatementCacheExpirederror.When enabled, Active Record will avoid wildcards and always include column names in
SELECTqueries, which will return consistent results and avoid prepared statement errors.Before:
Book.limit(5) # SELECT * FROM books LIMIT 5After:
# config/application.rb module MyApp class Application < Rails::Application config.active_record.enumerate_columns_in_select_statements = true end end # or, configure per-model class Book < ApplicationRecord self.enumerate_columns_in_select_statements = true endBook.limit(5) # SELECT id, author_id, name, format, status, language, etc FROM books LIMIT 5Matt Duszynski
-
Allow passing SQL as
on_duplicatevalue to#upsert_allto make it possible to use raw SQL to update columns on conflict:Book.upsert_all( [{ id: 1, status: 1 }, { id: 2, status: 1 }], on_duplicate: Arel.sql("status = GREATEST(books.status, EXCLUDED.status)") )Vladimir Dementyev
-
Allow passing SQL as
returningstatement to#upsert_all:Article.insert_all( [ { title: "Article 1", slug: "article-1", published: false }, { title: "Article 2", slug: "article-2", published: false } ], returning: Arel.sql("id, (xmax = '0') as inserted, name as new_name") )Vladimir Dementyev
-
Deprecate
legacy_connection_handling.Eileen M. Uchitelle
-
Add attribute encryption support.
Encrypted attributes are declared at the model level. These are regular Active Record attributes backed by a column with the same name. The system will transparently encrypt these attributes before saving them into the database and will decrypt them when retrieving their values.
class Person < ApplicationRecord encrypts :name encrypts :email_address, deterministic: true endYou can learn more in the Active Record Encryption guide.
Jorge Manrubia
-
Changed Arel predications
containsandoverlapsto usequoted_nodeso that PostgreSQL arrays are quoted properly.Bradley Priest
-
Add mode argument to record level
strict_loading!.This argument can be used when enabling strict loading for a single record to specify that we only want to raise on n plus one queries.
developer.strict_loading!(mode: :n_plus_one_only) developer.projects.to_a # Does not raise developer.projects.first.client # Raises StrictLoadingViolationErrorPreviously, enabling strict loading would cause any lazily loaded association to raise an error. Using
n_plus_one_onlymode allows us to lazily load belongs_to, has_many, and other associations that are fetched through a single query.Dinah Shi
-
Fix Float::INFINITY assignment to datetime column with postgresql adapter.
Before:
# With this config ActiveRecord::Base.time_zone_aware_attributes = true # and the following schema: create_table "postgresql_infinities" do |t| t.datetime "datetime" end # This test fails record = PostgresqlInfinity.create!(datetime: Float::INFINITY) assert_equal Float::INFINITY, record.datetime # record.datetime gets nilAfter this commit,
record.datetimegetsFloat::INFINITYas expected.Shunichi Ikegami
-
Type cast enum values by the original attribute type.
The notable thing about this change is that unknown labels will no longer match 0 on MySQL.
class Book < ActiveRecord::Base enum :status, { proposed: 0, written: 1, published: 2 } endBefore:
# SELECT `books`.* FROM `books` WHERE `books`.`status` = 'prohibited' LIMIT 1 Book.find_by(status: :prohibited) # => #<Book id: 1, status: "proposed", ...> (for mysql2 adapter) # => ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: invalid input syntax for type integer: "prohibited" (for postgresql adapter) # => nil (for sqlite3 adapter)After:
# SELECT `books`.* FROM `books` WHERE `books`.`status` IS NULL LIMIT 1 Book.find_by(status: :prohibited) # => nil (for all adapters)Ryuta Kamizono
-
Fixtures for
has_many :throughassociations now load timestamps on join tables.Given this fixture:
### monkeys.yml george: name: George the Monkey fruits: apple ### fruits.yml apple: name: appleIf the join table (
fruit_monkeys) containscreated_atorupdated_atcolumns, these will now be populated when loading the fixture. Previously, fixture loading would crash if these columns were required, and leave them as null otherwise.Alex Ghiculescu
-
Allow applications to configure the thread pool for async queries.
Some applications may want one thread pool per database whereas others want to use a single global thread pool for all queries. By default, Rails will set
async_query_executortonilwhich will not initialize any executor. Ifload_asyncis called and no executor has been configured, the query will be executed in the foreground.To create one thread pool for all database connections to use applications can set
config.active_record.async_query_executorto:global_thread_pooland optionally defineconfig.active_record.global_executor_concurrency. This defaults to 4. For applications that want to have a thread pool for each database connection,config.active_record.async_query_executorcan be set to:multi_thread_pool. The configuration for each thread pool is set in the database configuration.Eileen M. Uchitelle
-
Allow new syntax for
enumto avoid leading_from reserved options.Before:
class Book < ActiveRecord::Base enum status: [ :proposed, :written ], _prefix: true, _scopes: false enum cover: [ :hard, :soft ], _suffix: true, _default: :hard endAfter:
class Book < ActiveRecord::Base enum :status, [ :proposed, :written ], prefix: true, scopes: false enum :cover, [ :hard, :soft ], suffix: true, default: :hard endRyuta Kamizono
-
Add
ActiveRecord::Relation#load_async.This method schedules the query to be performed asynchronously from a thread pool.
If the result is accessed before a background thread had the opportunity to perform the query, it will be performed in the foreground.
This is useful for queries that can be performed long enough before their result will be needed, or for controllers which need to perform several independent queries.
def index @categories = Category.some_complex_scope.load_async @posts = Post.some_complex_scope.load_async endActive Record logs will also include timing info for the duration of how long the main thread had to wait to access the result. This timing is useful to know whether or not it's worth to load the query asynchronously.
DEBUG -- : Category Load (62.1ms) SELECT * FROM `categories` LIMIT 50 DEBUG -- : ASYNC Post Load (64ms) (db time 126.1ms) SELECT * FROM `posts` LIMIT 100The duration in the first set of parens is how long the main thread was blocked waiting for the results, and the second set of parens with "db time" is how long the entire query took to execute.
Jean Boussier
-
Implemented
ActiveRecord::Relation#excludingmethod.This method excludes the specified record (or collection of records) from the resulting relation:
Post.excluding(post) Post.excluding(post_one, post_two)Also works on associations:
post.comments.excluding(comment) post.comments.excluding(comment_one, comment_two)This is short-hand for
Post.where.not(id: post.id)(for a single record) andPost.where.not(id: [post_one.id, post_two.id])(for a collection).Glen Crawford
-
Skip optimised #exist? query when #include? is called on a relation with a having clause.
Relations that have aliased select values AND a having clause that references an aliased select value would generate an error when #include? was called, due to an optimisation that would generate call #exists? on the relation instead, which effectively alters the select values of the query (and thus removes the aliased select values), but leaves the having clause intact. Because the having clause is then referencing an aliased column that is no longer present in the simplified query, an ActiveRecord::InvalidStatement error was raised.
A sample query affected by this problem:
Author.select('COUNT(*) as total_posts', 'authors.*') .joins(:posts) .group(:id) .having('total_posts > 2') .include?(Author.first)This change adds an addition check to the condition that skips the simplified #exists? query, which simply checks for the presence of a having clause.
Fixes #41417.
Michael Smart
-
Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted without Rails knowledge (e.g., if app gets killed during long-running query or due to Rack::Timeout), app won't end up in perpetual crash state for being inconsistent with PostgreSQL.
wbharding, Martin Tepper
-
Add ability to apply
scopingtoall_queries.Some applications may want to use the
scopingmethod but previously it only worked on certain types of queries. This change allows thescopingmethod to apply to all queries for a model in a block.Post.where(blog_id: post.blog_id).scoping(all_queries: true) do post.update(title: "a post title") # adds `posts.blog_id = 1` to the query endEileen M. Uchitelle
-
ActiveRecord::Calculations.calculatecalled with:average(aliased asActiveRecord::Calculations.average) will now use column-based type casting. This means that floating-point number columns will now be aggregated asFloatand decimal columns will be aggregated asBigDecimal.Integers are handled as a special case returning
BigDecimalalways (this was the case before already).# With the following schema: create_table "measurements" do |t| t.float "temperature" end # Before: Measurement.average(:temperature).class # => BigDecimal # After: Measurement.average(:temperature).class # => FloatBefore this change, Rails just called
to_don average aggregates from the database adapter. This is not the case anymore. If you relied on that kind of magic, you now need to register your ownActiveRecord::Type(seeActiveRecord::Attributes::ClassMethodsfor documentation).Josua Schmid
-
PostgreSQL: introduce
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_type.This setting controls what native type Active Record should use when you call
datetimein a migration or schema. It takes a symbol which must correspond to one of the configuredNATIVE_DATABASE_TYPES. The default is:timestamp, meaningt.datetimein a migration will create a "timestamp without time zone" column. To use "timestamp with time zone", change this to:timestamptzin an initializer.You should run
bin/rails db:migrateto rebuild your schema.rb if you change this.Alex Ghiculescu
-
PostgreSQL: handle
timestamp with time zonecolumns correctly inschema.rb.Previously they dumped as
t.datetime :column_name, now they dump ast.timestamptz :column_name, and are created astimestamptzcolumns when the schema is loaded.Alex Ghiculescu
-
Removing trailing whitespace when matching columns in
ActiveRecord::Sanitization.disallow_raw_sql!.Gannon McGibbon, Adrian Hirt
-
Expose a way for applications to set a
primary_abstract_class.Multiple database applications that use a primary abstract class that is not named
ApplicationRecordcan now set a specific class to be theprimary_abstract_class.class PrimaryApplicationRecord self.primary_abstract_class endWhen an application boots it automatically connects to the primary or first database in the database configuration file. In a multiple database application that then call
connects_toneeds to know that the default connection is the same as theApplicationRecordconnection. However, some applications have a differently namedApplicationRecord. This prevents Active Record from opening duplicate connections to the same database.Eileen M. Uchitelle, John Crepezzi
-
Support hash config for
structure_dump_flagsandstructure_load_flagsflags. Now that Active Record supports multiple databases configuration, we need a way to pass specific flags for dump/load databases since the options are not the same for different adapters. We can use in the original way:ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-defaults', '--skip-add-drop-table'] # or ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = '--no-defaults --skip-add-drop-table'And also use it passing a hash, with one or more keys, where the key is the adapter
ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = { mysql2: ['--no-defaults', '--skip-add-drop-table'], postgres: '--no-tablespaces' }Gustavo Gonzalez
-
Connection specification now passes the "url" key as a configuration for the adapter if the "url" protocol is "jdbc", "http", or "https". Previously only urls with the "jdbc" prefix were passed to the Active Record Adapter, others are assumed to be adapter specification urls.
Fixes #41137.
Jonathan Bracy
-
Allow to opt-out of
strict_loadingmode on a per-record base.This is useful when strict loading is enabled application wide or on a model level.
class User < ApplicationRecord has_many :bookmarks has_many :articles, strict_loading: true end user = User.first user.articles # => ActiveRecord::StrictLoadingViolationError user.bookmarks # => #<ActiveRecord::Associations::CollectionProxy> user.strict_loading!(true) # => true user.bookmarks # => ActiveRecord::StrictLoadingViolationError user.strict_loading!(false) # => false user.bookmarks # => #<ActiveRecord::Associations::CollectionProxy> user.articles.strict_loading!(false) # => #<ActiveRecord::Associations::CollectionProxy>Ayrton De Craene
-
Add
FinderMethods#soleand#find_sole_byto find and assert the presence of exactly one record.Used when you need a single row, but also want to assert that there aren't multiple rows matching the condition; especially for when database constraints aren't enough or are impractical.
Product.where(["price = %?", price]).sole # => ActiveRecord::RecordNotFound (if no Product with given price) # => #<Product ...> (if one Product with given price) # => ActiveRecord::SoleRecordExceeded (if more than one Product with given price) user.api_keys.find_sole_by(key: key) # as aboveAsherah Connor
-
Makes
ActiveRecord::AttributeMethods::Queryrespect the getter overrides defined in the model.Before:
class User def admin false # Overriding the getter to always return false end end user = User.first user.update(admin: true) user.admin # false (as expected, due to the getter overwrite) user.admin? # true (not expected, returned the DB column value)After this commit,
user.admin?above returns false, as expected.Fixes #40771.
Felipe
-
Allow delegated_type to be specified primary_key and foreign_key.
Since delegated_type assumes that the foreign_key ends with
_id,singular_iddefined by it does not work when the foreign_key does not end withid. This change fixes it by taking into accountprimary_keyandforeign_keyin the options.Ryota Egusa
-
Expose an
invert_wheremethod that will invert all scope conditions.class User scope :active, -> { where(accepted: true, locked: false) } end User.active # ... WHERE `accepted` = 1 AND `locked` = 0 User.active.invert_where # ... WHERE NOT (`accepted` = 1 AND `locked` = 0)Kevin Deisz
-
Restore possibility of passing
falseto :polymorphic option ofbelongs_to.Previously, passing
falsewould trigger the option validation logic to throw an error saying :polymorphic would not be a valid option.glaszig
-
Remove deprecated
databasekwarg fromconnected_to.Eileen M. Uchitelle, John Crepezzi
-
Allow adding nonnamed expression indexes to be revertible.
Previously, the following code would raise an error, when executed while rolling back, and the index name should be specified explicitly. Now, the index name is inferred automatically.
add_index(:items, "to_tsvector('english', description)")Fixes #40732.
fatkodima
-
Only warn about negative enums if a positive form that would cause conflicts exists.
Fixes #39065.
Alex Ghiculescu
-
Add option to run
default_scopeon all queries.Previously, a
default_scopewould only run on select or insert queries. In some cases, like non-Rails tenant sharding solutions, it may be desirable to rundefault_scopeon all queries in order to ensure queries are including a foreign key for the shard (i.e.blog_id).Now applications can add an option to run on all queries including select, insert, delete, and update by adding an
all_queriesoption to the default scope definition.class Article < ApplicationRecord default_scope -> { where(blog_id: Current.blog.id) }, all_queries: true endEileen M. Uchitelle
-
Add
where.associatedto check for the presence of an association.# Before: account.users.joins(:contact).where.not(contact_id: nil) # After: account.users.where.associated(:contact)Also mirrors
where.missing.Kasper Timm Hansen
-
Allow constructors (
build_associationandcreate_association) onhas_one :throughassociations.Santiago Perez Perret
Active Storage
-
Support transforming empty-ish
has_many_attachedvalue into[](e.g.[""]).@user.highlights = [""] @user.highlights # => []Sean Doyle
-
Add ActiveStorage::Blob.composeto concatenate multiple blobs.Gannon McGibbon
-
Setting custom metadata on blobs are now persisted to remote storage.
joshuamsager
-
Support direct uploads to multiple services.
Dmitry Tsepelev
-
Invalid default content types are deprecated
Blobs created with content_type
image/jpg,image/pjpeg,image/bmp,text/javascriptwill now produce a deprecation warning, since these are not valid content types.These content types will be removed from the defaults in Rails 7.1.
You can set
config.active_storage.silence_invalid_content_types_warning = trueto dismiss the warning.Alex Ghiculescu
-
Emit Active Support instrumentation events from Active Storage analyzers.
Fixes #42930
Shouichi Kamiya
-
Add support for byte range requests
Tom Prats
-
Attachments can be deleted after their association is no longer defined.
Fixes #42514
Don Sisco
-
Make
vipsthe default variant processor for new apps.See the upgrade guide for instructions on converting from
mini_magicktovips.mini_magickis not deprecated, existing apps can keep using it.Breno Gazzola
-
Deprecate
ActiveStorage::Current.hostin favor ofActiveStorage::Current.url_optionswhich accepts a host, protocol and port.Santiago Bartesaghi
-
Allow using IAM when signing URLs with GCS.
gcs: service: GCS ... iam: trueRRethy
-
OpenSSL constants are now used for Digest computations.
Dirkjan Bussink
-
Deprecate
config.active_storage.replace_on_assign_to_many. Future versions of Rails will behave the same way as when the config is set totrue.Santiago Bartesaghi
-
Remove deprecated methods:
build_after_upload,create_after_upload!in favor ofcreate_and_upload!, andservice_urlin favor ofurl.Santiago Bartesaghi
-
Add support of
strict_loading_by_defaulttoActiveStorage::Representationscontrollers.Anton Topchii, Andrew White
-
Allow to detach an attachment when record is not persisted.
Jacopo Beschi
-
Use libvips instead of ImageMagick to analyze images when
active_storage.variant_processor = vips.Breno Gazzola
-
Add metadata value for presence of video channel in video blobs.
The
metadataattribute of video blobs has a new boolean key namedvideothat is set totrueif the file has an video channel andfalseif it doesn't.Breno Gazzola
-
Deprecate usage of
purgeandpurge_laterfrom the association extension.Jacopo Beschi
-
Passing extra parameters in
ActiveStorage::Blob#urlto S3 Client.This allows calls of
ActiveStorage::Blob#urlto have more interaction with the S3 Presigner, enabling, amongst other options, custom S3 domain URL Generation.blob = ActiveStorage::Blob.last blob.url # => https://<bucket-name>.s3.<region>.amazonaws.com/<key> blob.url(virtual_host: true) # => # => https://<bucket-name>/<key>josegomezr
-
Allow setting a
Cache-Controlon files uploaded to GCS.gcs: service: GCS ... cache_control: "public, max-age=3600"maleblond
-
The parameters sent to
ffmpegfor generating a video preview image are now configurable underconfig.active_storage.video_preview_arguments.Brendon Muir
-
The ActiveStorage video previewer will now use scene change detection to generate better preview images (rather than the previous default of using the first frame of the video). This change requires FFmpeg v3.4+.
Jonathan Hefner
-
Add support for ActiveStorage expiring URLs.
rails_blob_path(user.avatar, disposition: "attachment", expires_in: 30.minutes) <%= image_tag rails_blob_path(user.avatar.variant(resize: "100x100"), expires_in: 30.minutes) %>If you want to set default expiration time for ActiveStorage URLs throughout your application, set
config.active_storage.urls_expire_in.aki77
-
Allow to purge an attachment when record is not persisted for
has_many_attached.Jacopo Beschi
-
Add
with_all_variant_recordsmethod to eager load all variant records on an attachment at once.with_attached_imagescope now eager loads variant records if using variant tracking.Alex Ghiculescu
-
Add metadata value for presence of audio channel in video blobs.
The
metadataattribute of video blobs has a new boolean key namedaudiothat is set totrueif the file has an audio channel andfalseif it doesn't.Breno Gazzola
-
Adds analyzer for audio files.
Breno Gazzola
-
Respect Active Record's primary_key_type in Active Storage migrations.
fatkodima
-
Allow
expires_infor ActiveStorage signed ids.aki77
-
Allow to purge an attachment when record is not persisted for
has_one_attached.Jacopo Beschi
-
Add a load hook called
active_storage_variant_record(providingActiveStorage::VariantRecord) to allow for overriding aspects of theActiveStorage::VariantRecordclass. This makesActiveStorage::VariantRecordconsistent withActiveStorage::BlobandActiveStorage::Attachmentthat already have load hooks.Brendon Muir
-
ActiveStorage::PreviewErroris raised when a previewer is unable to generate a preview image.Alex Robbin
-
Add
ActiveStorage::Streamingmodule that can be included in a controller to get access to#send_blob_stream, which wraps the newActionController::Base#send_streammethod to stream a blob from cloud storage:class MyPublicBlobsController < ApplicationController include ActiveStorage::SetBlob, ActiveStorage::Streaming def show http_cache_forever(public: true) do send_blob_stream @blob, disposition: params[:disposition] end end endDHH
-
Add ability to use pre-defined variants.
class User < ActiveRecord::Base has_one_attached :avatar do |attachable| attachable.variant :thumb, resize: "100x100" attachable.variant :medium, resize: "300x300", monochrome: true end end class Gallery < ActiveRecord::Base has_many_attached :photos do |attachable| attachable.variant :thumb, resize: "100x100" attachable.variant :medium, resize: "300x300", monochrome: true end end <%= image_tag user.avatar.variant(:thumb) %>fatkodima
-
After setting
config.active_storage.resolve_model_to_route = :rails_storage_proxyrails_blob_pathandrails_representation_pathwill generate proxy URLs by default.Ali Ismayilov
-
Declare
ActiveStorage::FixtureSetandActiveStorage::FixtureSet.blobto improve fixture integration.Sean Doyle
Active Support
-
Fix
ActiveSupport::Duration.buildto support negative values.The algorithm to collect the
partsof theActiveSupport::Durationignored the sign of thevalueand accumulated incorrect part values. This impactedActiveSupport::Duration#sum(which is dependent onparts) but notActiveSupport::Duration#eql?(which is dependent onvalue).Caleb Buxton, Braden Staudacher
-
Deprecate passing a format to
#to_sin favor of#to_formatted_sinArray,Range,Date,DateTime,Time,BigDecimal,Floatand,Integer.Rafael Mendonça França
-
Document
ActiveSupport::Testing::Deprecation.Sam Bostock & Sam Jordan
-
Add
Pathname#existence.Pathname.new("file").existence&.readTimo Schilling
-
Remove deprecate
ActiveSupport::Multibyte::Unicode.default_normalization_form.Rafael Mendonça França
-
Remove deprecated support to use
Range#include?to check the inclusion of a value in a date time range is deprecated.Rafael Mendonça França
-
Remove deprecated
URI.parser.Rafael Mendonça França
-
Remove deprecated
config.active_support.use_sha1_digests.Rafael Mendonça França
-
Invoking
Object#with_optionswithout a&blockargument returns theActiveSupport::OptionMergerinstance.Sean Doyle
-
Rails.application.executorhooks can now be called around every testThis helps to better simulate request or job local state being reset around tests and prevents state leaking from one test to another.
However it requires the executor hooks executed in the test environment to be re-entrant.
To enable this, set
config.active_support.executor_around_test_case = true(this is the default in Rails 7).Jean Boussier
-
ActiveSupport::DescendantsTrackernow mostly delegate toClass#descendantson Ruby 3.1Ruby now provides a fast
Class#descendantsmakingActiveSupport::DescendantsTrackermostly useless.As a result the following methods are deprecated:
ActiveSupport::DescendantsTracker.direct_descendantsActiveSupport::DescendantsTracker#direct_descendants
Jean Boussier
-
Fix the
Digest::UUID.uuid_from_hashbehavior for namespace IDs that are different from the ones defined onDigest::UUID.The new behavior will be enabled by setting the
config.active_support.use_rfc4122_namespaced_uuidsoption totrueand is the default for new apps.The old behavior is the default for upgraded apps and will output a deprecation warning every time a value that is different than one of the constants defined on the
Digest::UUIDextension is used as the namespace ID.Alex Robbin, Erich Soares Machado, Eugene Kenny
-
ActiveSupport::Inflector::Inflections#clear(:acronyms)is now supported, andinflector.clear/inflector.clear(:all)also clears acronyms.Alex Ghiculescu, Oliver Peate
-
ActiveSupport::Dependenciesno longer installs aconst_missinghook. Before this, you could push to the autoload paths and have constants autoloaded. This feature, known as theclassicautoloader, has been removed.Xavier Noria
-
Private internal classes of
ActiveSupport::Dependencieshave been deleted, likeActiveSupport::Dependencies::Reference,ActiveSupport::Dependencies::Blamable, and others.Xavier Noria
-
The private API of
ActiveSupport::Dependencieshas been deleted. That includes methods likehook!,unhook!,depend_on,require_or_load,mechanism, and many others.Xavier Noria
-
Improves the performance of
ActiveSupport::NumberHelperformatters by avoiding the use of exceptions as flow control.Mike Dalessio
-
Removed rescue block from
ActiveSupport::Cache::RedisCacheStore#handle_exceptionPreviously, if you provided a
error_handlertoredis_cache_store, any errors thrown by the error handler would be rescued and logged only. Removed therescueclause fromhandle_exceptionto allow these to be thrown.Nicholas A. Stuart
-
Allow entirely opting out of deprecation warnings.
Previously if you did
app.config.active_support.deprecation = :silence, some work would still be done on each call toActiveSupport::Deprecation.warn. In very hot paths, this could cause performance issues.Now, you can make
ActiveSupport::Deprecation.warna no-op:config.active_support.report_deprecations = falseThis is the default in production for new apps. It is the equivalent to:
config.active_support.deprecation = :silence config.active_support.disallowed_deprecation = :silencebut will take a more optimised code path.
Alex Ghiculescu
-
Faster tests by parallelizing only when overhead is justified by the number of them.
Running tests in parallel adds overhead in terms of database setup and fixture loading. Now, Rails will only parallelize test executions when there are enough tests to make it worth it.
This threshold is 50 by default, and is configurable via config setting in your test.rb:
config.active_support.test_parallelization_threshold = 100It's also configurable at the test case level:
class ActiveSupport::TestCase parallelize threshold: 100 endJorge Manrubia
-
OpenSSL constants are now used for Digest computations.
Dirkjan Bussink
-
TimeZone.iso8601now accepts valid ordinal values similar to Ruby'sDate._iso8601method. A valid ordinal value will be converted to an instance ofTimeWithZoneusing the:yearand:ydayfragments returned fromDate._iso8601.twz = ActiveSupport::TimeZone["Eastern Time (US & Canada)"].iso8601("21087") twz.to_a[0, 6] == [0, 0, 0, 28, 03, 2021]Steve Laing
-
Time#changeand methods that call it (e.g.Time#advance) will now return aTimewith the timezone argument provided, if the caller was initialized with a timezone argument.Fixes #42467.
Alex Ghiculescu
-
Allow serializing any module or class to JSON by name.
Tyler Rick, Zachary Scott
-
Raise
ActiveSupport::EncryptedFile::MissingKeyErrorwhen theRAILS_MASTER_KEYenvironment variable is blank (e.g."").Sunny Ripert
-
The
from:option is added toActiveSupport::TestCase#assert_no_changes.It permits asserting on the initial value that is expected not to change.
assert_no_changes -> { Status.all_good? }, from: true do post :create, params: { status: { ok: true } } endGeorge Claghorn
-
Deprecate
ActiveSupport::SafeBuffer's incorrect implicit conversion of objects into string.Except for a few methods like
String#%, objects must implement#to_strto be implicitly converted to a String in string operations. In some circumstancesActiveSupport::SafeBufferwas incorrectly calling the explicit conversion method (#to_s) on them. This behavior is now deprecated.Jean Boussier
-
Allow nested access to keys on
Rails.application.credentials.Previously only top level keys in
credentials.yml.enccould be accessed with method calls. Now any key can.For example, given these secrets:
aws: access_key_id: 123 secret_access_key: 345Rails.application.credentials.aws.access_key_idwill now return the same thing asRails.application.credentials.aws[:access_key_id].Alex Ghiculescu
-
Added a faster and more compact
ActiveSupport::Cacheserialization format.It can be enabled with
config.active_support.cache_format_version = 7.0orconfig.load_defaults 7.0. Regardless of the configuration Active Support 7.0 can read cache entries serialized by Active Support 6.1 which allows to upgrade without invalidating the cache. However Rails 6.1 can't read the new format, so all readers must be upgraded before the new format is enabled.Jean Boussier
-
Add
Enumerable#sole, perActiveRecord::FinderMethods#sole. Returns the sole item of the enumerable, raising if no items are found, or if more than one is.Asherah Connor
-
Freeze
ActiveSupport::Duration#partsand remove writer methods.Durations are meant to be value objects and should not be mutated.
Andrew White
-
Fix
ActiveSupport::TimeZone#utc_to_localwith fractional seconds.When
utc_to_local_returns_utc_offset_timesis false and the time instance had fractional seconds the new UTC time instance was out by a factor of 1,000,000 as theTime.utcconstructor takes a usec value and not a fractional second value.Andrew White
-
Add
expires_atargument toActiveSupport::Cachewriteandfetchto set a cache entry TTL as an absolute time.Rails.cache.write(key, value, expires_at: Time.now.at_end_of_hour)Jean Boussier
-
Deprecate
ActiveSupport::TimeWithZone.nameso that from Rails 7.1 it will use the default implementation.Andrew White
-
Deprecates Rails custom
Enumerable#sumandArray#sumin favor of Ruby's native implementation which is considerably faster.Ruby requires an initializer for non-numeric type as per examples below:
%w[foo bar].sum('') # instead of %w[foo bar].sum [[1, 2], [3, 4, 5]].sum([]) # instead of [[1, 2], [3, 4, 5]].sumAlberto Mota
-
Tests parallelization is now disabled when running individual files to prevent the setup overhead.
It can still be enforced if the environment variable
PARALLEL_WORKERSis present and set to a value greater than 1.Ricardo Díaz
-
Fix proxying keyword arguments in
ActiveSupport::CurrentAttributes.Marcin Kołodziej
-
Add
Enumerable#maximumandEnumerable#minimumto easily calculate the maximum or minimum from extracted elements of an enumerable.payments = [Payment.new(5), Payment.new(15), Payment.new(10)] payments.minimum(:price) # => 5 payments.maximum(:price) # => 15This also allows passing enumerables to
fresh_whenandstale?in Action Controller. See PR #41404 for an example.Ayrton De Craene
-
ActiveSupport::Cache::MemCacheStorenow accepts an explicitnilfor itsaddressesargument.config.cache_store = :mem_cache_store, nil # is now equivalent to config.cache_store = :mem_cache_store # and is also equivalent to config.cache_store = :mem_cache_store, ENV["MEMCACHE_SERVERS"] || "localhost:11211" # which is the fallback behavior of DalliThis helps those migrating from
:dalli_store, where an explicitnilwas permitted.Michael Overmeyer
-
Add
Enumerable#in_order_ofto put an Enumerable in a certain order by a key.DHH
-
ActiveSupport::Inflector.camelizebehaves expected when provided a symbol:upperor:lowerargument. MatchesString#camelizebehavior.Alex Ghiculescu
-
Raises an
ArgumentErrorwhen the first argument ofActiveSupport::Notification.subscribeis invalid.Vipul A M
-
HashWithIndifferentAccess#deep_transform_keysnow returns aHashWithIndifferentAccessinstead of aHash.Nathaniel Woodthorpe
-
Consume dalli’s
cache_nilsconfiguration asActiveSupport::Cache'sskip_nilwhen usingMemCacheStore.Ritikesh G
-
Add
RedisCacheStore#statsmethod similar toMemCacheStore#stats. Callsredis#infointernally.Ritikesh G
Guides
-
The autoloading guide for
zeitwerkmode has been revised.Xavier Noria
-
The autoloading guide for
classicmode has been deleted.Xavier Noria
Railtie
-
Allow localhost with a port by default in development
[Fixes: #43864]
-
Remove deprecated
configindbconsole.Rafael Mendonça França
-
Change default
X-XSS-Protectionheader to disable XSS auditorThis header has been deprecated and the XSS auditor it triggered has been removed from all major modern browsers (in favour of Content Security Policy) that implemented this header to begin with (Firefox never did).
OWASP suggests setting this header to '0' to disable the default behaviour on old browsers as it can introduce additional security issues.
Added the new behaviour as a framework default from Rails 7.0.
Christian Sutter
-
Scaffolds now use date_field, time_field and datetime_field instead of date_select, time_select and datetime_select; thus providing native date/time pickers.
Martijn Lafeber
-
Fix a regression in which autoload paths were initialized too late.
Xavier Noria
-
Fix activestorage dependency in the npm package.
Rafael Mendonça França
-
New and upgraded Rails apps no longer generate
config/initializers/application_controller_renderer.rborconfig/initializers/cookies_serializer.rbThe default value for
cookies_serializer(:json) has been moved toconfig.load_defaults("7.0"). The new framework defaults file can be used to upgrade the serializer.Alex Ghiculescu
-
New applications get a dependency on the new
debuggem, replacingbyebug.Xavier Noria
-
Add SSL support for postgresql in
bin/rails dbconsole.Fixes #43114.
Michael Bayucot
-
Add support for comments above gem declaration in Rails application templates, e.g.
gem("nokogiri", comment: "For XML").Linas Juškevičius
-
The setter
config.autoloader=has been deleted.zeitwerkis the only available autoloading mode.Xavier Noria
-
config.autoload_once_pathscan be configured in the body of the application class defined inconfig/application.rbor in the configuration for environments inconfig/environments/*.Similarly, engines can configure that collection in the class body of the engine class or in the configuration for environments.
After that, the collection is frozen, and you can autoload from those paths. They are managed by the
Rails.autoloaders.onceautoloader, which does not reload, only autoloads/eager loads.Xavier Noria
-
During initialization, you cannot autoload reloadable classes or modules like application models, unless they are wrapped in a
to_prepareblock. For example, fromconfig/initializers/*, or in application, engines, or railties initializers.Please check the autoloading guide for details.
Xavier Noria
-
While they are allowed to have elements in common, it is no longer required that
config.autoload_once_pathsis a subset ofconfig.autoload_paths. The former are managed by theonceautoloader. Themainautoloader manages the latter minus the former.Xavier Noria
-
Show Rake task description if command is run with
-h.Adding
-h(or--help) to a Rails command that's a Rake task now outputs the task description instead of the general Rake help.Petrik de Heus
-
Add missing
plugin newcommand to help.*Petrik de Heus
-
Fix
config_forerror when there's only a shared root array.Loïc Delmaire
-
Raise an error in generators if an index type is invalid.
Petrik de Heus
-
package.jsonnow uses a strict version constraint for Rails JavaScript packages on new Rails apps.Zachary Scott, Alex Ghiculescu
-
Modified scaffold generator template so that running
rails g scaffold Authorno longer generates tests called "creating a Author", "updating a Author", and "destroying a Author".Fixes #40744.
Michael Duchemin
-
Raise an error in generators if a field type is invalid.
Petrik de Heus
-
bin/rails tmp:cleardeletes also files and directories intmp/storage.George Claghorn
-
Fix compatibility with
psych >= 4.Starting in Psych 4.0.0
YAML.loadbehaves likeYAML.safe_load. To preserve compatibilityRails.application.config_fornow usesYAML.unsafe_loadif available.Jean Boussier
-
Allow loading nested locales in engines.
Gannon McGibbon
-
Ensure
Rails.application.config_foralways cast hashes toActiveSupport::OrderedOptions.Jean Boussier
-
Remove
Rack::Runtimefrom the default middleware stack and deprecate referencing it in middleware operations without adding it back.Hartley McGuire
-
Allow adding additional authorized hosts in development via
ENV['RAILS_DEVELOPMENT_HOSTS'].Josh Abernathy, Debbie Milburn
-
Add app concern and test keepfiles to generated engine plugins.
Gannon McGibbon
-
Stop generating a license for in-app plugins.
Gannon McGibbon
-
rails app:updateno longer prompts you to overwrite files that are generally modified in the course of developing a Rails app. See #41083 for the full list of changes.Alex Ghiculescu
-
Change default branch for new Rails projects and plugins to
main.Prateek Choudhary
-
The new method
Rails.benchmarkgives you a quick way to measure and log the execution time taken by a block:def test_expensive_stuff Rails.benchmark("test_expensive_stuff") { ... } endThis functionality was available in some contexts only before.
Simon Perepelitsa
-
Applications generated with
--skip-sprocketsno longer getapp/assets/config/manifest.jsandapp/assets/stylesheets/application.css.Cindy Gao
-
Add support for stylesheets and ERB views to
rails stats.Joel Hawksley
-
Allow appended root routes to take precedence over internal welcome controller.
Gannon McGibbon
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Symbol is allowed by default for YAML columns
Étienne Barrié
-
Fix
ActiveRecord::Storeto serialize as a regular HashPreviously it would serialize as an
ActiveSupport::HashWithIndifferentAccesswhich is wasteful and cause problem with YAML safe_load.Jean Boussier
-
Fix PG.connect keyword arguments deprecation warning on ruby 2.7
Fixes #44307.
Nikita Vasilevsky
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Respect Active Record's primary_key_type in Active Storage migrations. Backported from 7.0.
fatkodima
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Active Support
-
Fix and add protections for XSS in
ActionView::HelpersandERB::Util.Add the method
ERB::Util.xml_name_escapeto escape dangerous characters in names of tags and names of attributes, following the specification of XML.Álvaro Martín Fraguas
Active Model
- No changes.
Active Record
- No changes.
Action View
-
Fix and add protections for XSS in
ActionView::HelpersandERB::Util.Escape dangerous characters in names of tags and names of attributes in the tag helpers, following the XML specification. Rename the option
:escape_attributesto:escape, to simplify by applying the option to the whole tag.Álvaro Martín Fraguas
Action Pack
-
Allow Content Security Policy DSL to generate for API responses.
Tim Wade
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Active Support
-
Fix
ActiveSupport::Duration.buildto support negative values.The algorithm to collect the
partsof theActiveSupport::Durationignored the sign of thevalueand accumulated incorrect part values. This impactedActiveSupport::Duration#sum(which is dependent onparts) but notActiveSupport::Duration#eql?(which is dependent onvalue).Caleb Buxton, Braden Staudacher
-
Time#changeand methods that call it (eg.Time#advance) will now return aTimewith the timezone argument provided, if the caller was initialized with a timezone argument.Fixes #42467.
Alex Ghiculescu
-
Clone to keep extended Logger methods for tagged logger.
Orhan Toy
-
assert_changesworks on includingActiveSupport::Assertionsmodule.Pedro Medeiros
Active Model
-
Clear secure password cache if password is set to
nilBefore:
user.password = 'something' user.password = nil
user.password # => 'something'
Now:
user.password = 'something' user.password = nil
user.password # => nil
Markus Doits
-
Fix delegation in
ActiveModel::Type::Registry#lookupandActiveModel::Type.lookupPassing a last positional argument
{}would be incorrectly considered as keyword argument.Benoit Daloze
-
Fix
to_jsonafterchanges_appliedforActiveModel::Dirtyobject.Ryuta Kamizono
Active Record
-
Fix
ActiveRecord::ConnectionAdapters::SchemaCache#deep_deduplicatefor Ruby 2.6.Ruby 2.6 and 2.7 have slightly different implementations of the
String#@-method. In Ruby 2.6, the receiver of theString#@-method is modified under certain circumstances. This was later identified as a bug (https://bugs.ruby-lang.org/issues/15926) and only fixed in Ruby 2.7.Before the changes in this commit, the
ActiveRecord::ConnectionAdapters::SchemaCache#deep_deduplicatemethod, which internally calls theString#@-method, could also modify an input string argument in Ruby 2.6 -- changing a tainted, unfrozen string into a tainted, frozen string.Fixes #43056
Eric O'Hanlon
-
Fix migration compatibility to create SQLite references/belongs_to column as integer when migration version is 6.0.
reference/belongs_toin migrations with version 6.0 were creating columns as bigint instead of integer for the SQLite Adapter.Marcelo Lauxen
-
Fix dbconsole for 3-tier config.
Eileen M. Uchitelle
-
Better handle SQL queries with invalid encoding.
Post.create(name: "broken \xC8 UTF-8")Would cause all adapters to fail in a non controlled way in the code responsible to detect write queries.
The query is now properly passed to the database connection, which might or might not be able to handle it, but will either succeed or failed in a more correct way.
Jean Boussier
-
Ignore persisted in-memory records when merging target lists.
Kevin Sjöberg
-
Fix regression bug that caused ignoring additional conditions for preloading
has_manythrough relations.Fixes #43132
Alexander Pauly
-
Fix
ActiveRecord::InternalMetadatato not be broken byconfig.active_record.record_timestamps = falseSince the model always create the timestamp columns, it has to set them, otherwise it breaks various DB management tasks.
Fixes #42983
Jean Boussier
-
Fix duplicate active record objects on
inverse_of.Justin Carvalho
-
Fix duplicate objects stored in has many association after save.
Fixes #42549.
Alex Ghiculescu
-
Fix performance regression in
CollectionAssocation#build.Alex Ghiculescu
-
Fix retrieving default value for text column for MariaDB.
fatkodima
Action View
-
preload_link_tagproperly insertsasattributes for files withimageMIME types, such as JPG or SVG.Nate Berkopec
-
Add
autocomplete="off"to all generated hidden fields.Fixes #42610.
Ryan Baumann
-
Fix
current_page?when URL has trailing slash.This fixes the
current_page?helper when the given URL has a trailing slash, and is an absolute URL or also has query params.Fixes #33956.
Jonathan Hefner
Action Pack
-
Fix
content_security_policyreturning invalid directives.Directives such as
self,unsafe-evaland few others were not single quoted when the directive was the result of calling a lambda returning an array.content_security_policy do |policy| policy.frame_ancestors lambda { [:self, "https://example.com"] } endWith this fix the policy generated from above will now be valid.
Edouard Chin
-
Update
HostAuthorizationmiddleware to render debug info only whenconfig.consider_all_requests_localis set to true.Also, blocked host info is always logged with level
error.Fixes #42813.
Nikita Vyrko
-
Dup arrays that get "converted".
Fixes #43681.
Aaron Patterson
-
Don't show deprecation warning for equal paths.
Anton Rieder
-
Fix crash in
ActionController::Instrumentationwith invalid HTTP formats.Fixes #43094.
Alex Ghiculescu
-
Add fallback host for SystemTestCase driven by RackTest.
Fixes #42780.
Petrik de Heus
-
Add more detail about what hosts are allowed.
Alex Ghiculescu
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
-
The Action Cable client now ensures successful channel subscriptions:
- The client maintains a set of pending subscriptions until either the server confirms the subscription or the channel is torn down.
- Rectifies the race condition where an unsubscribe is rapidly followed by a subscribe (on the same channel identifier) and the requests are handled out of order by the ActionCable server, thereby ignoring the subscribe command.
Daniel Spinosa
-
Truncate broadcast logging messages.
J Smith
Active Storage
-
Attachments can be deleted after their association is no longer defined.
Fixes #42514
Don Sisco
Action Mailbox
-
Add
attachmentsto the list of permitted parameters for inbound emails conductor.When using the conductor to test inbound emails with attachments, this prevents an unpermitted parameter warning in default configurations, and prevents errors for applications that set:
config.action_controller.action_on_unpermitted_parameters = :raiseDavid Jones, Dana Henke
Action Text
-
Fix Action Text extra trix content wrapper.
Alexandre Ruban
Railties
-
In
zeitwerkmode, setup theonceautoloader first, and themainautoloader after it. This order plays better with shared namespaces.Xavier Noria
-
Handle paths with spaces when editing credentials.
Alex Ghiculescu
-
Support Psych 4 when loading secrets.
Nat Morcos
Active Support
-
MemCacheStore: convert any underlying value (including
false) to anEntry.See #42559.
Alex Ghiculescu
-
Fix bug in
number_with_precisionwhen using largeBigDecimalvalues.Fixes #42302.
Federico Aldunate, Zachary Scott
-
Check byte size instead of length on
secure_compare.Tietew
-
Fix
Time.atto not lose:inoption.Ryuta Kamizono
-
Require a path for
config.cache_store = :file_store.Alex Ghiculescu
-
Avoid having to store complex object in the default translation file.
Rafael Mendonça França
Active Model
-
Fix
to_jsonforActiveModel::Dirtyobject.Exclude +mutations_from_database+ attribute from json as it lead to recursion.
Anil Maurya
Active Record
-
Do not try to rollback transactions that failed due to a
ActiveRecord::TransactionRollbackError.Jamie McCarthy
-
Raise an error if
pool_configisnilinset_pool_config.Eileen M. Uchitelle
-
Fix compatibility with
psych >= 4.Starting in Psych 4.0.0
YAML.loadbehaves likeYAML.safe_load. To preserve compatibility Active Record's schema cache loader andYAMLColumnnow usesYAML.unsafe_loadif available.Jean Boussier
-
Support using replicas when using
rails dbconsole.Christopher Thornton
-
Restore connection pools after transactional tests.
Eugene Kenny
-
Change
upsert_allto fails cleanly for MySQL when:unique_byis used.Bastian Bartmann
-
Fix user-defined
self.default_scopeto respect table alias.Ryuta Kamizono
-
Clear
@cache_keyscache afterupdate_all,delete_all,destroy_all.Ryuta Kamizono
-
Changed Arel predications
containsandoverlapsto usequoted_nodeso that PostgreSQL arrays are quoted properly.Bradley Priest
-
Fix
mergewhen thewhereclauses have string contents.Ryuta Kamizono
-
Fix rollback of parent destruction with nested
dependent: :destroy.Jacopo Beschi
-
Fix binds logging for
"WHERE ... IN ..."statements.Ricardo Díaz
-
Handle
falsein relation strict loading checks.Previously when a model had strict loading set to true and then had a relation set
strict_loadingto false the false wasn't considered when deciding whether to raise/warn about strict loading.class Dog < ActiveRecord::Base self.strict_loading_by_default = true has_many :treats, strict_loading: false endIn the example,
dog.treatswould still raise even thoughstrict_loadingwas set to false. This is a bug effecting more than Active Storage which is why I made this PR superceeding #41461. We need to fix this for all applications since the behavior is a little surprising. I took the test from ##41461 and the code suggestion from #41453 with some additions.Eileen M. Uchitelle, Radamés Roriz
-
Fix numericality validator without precision.
Ryuta Kamizono
-
Fix aggregate attribute on Enum types.
Ryuta Kamizono
-
Fix
CREATE INDEXstatement generation for PostgreSQL.eltongo
-
Fix where clause on enum attribute when providing array of strings.
Ryuta Kamizono
-
Fix
unprepared_statementto work it when nesting.Ryuta Kamizono
Action View
-
The
translatehelper now passesdefaultvalues that aren't translation keys throughI18n.translatefor interpolation.Jonathan Hefner
-
Don't attach UJS form submission handlers to Turbo forms.
David Heinemeier Hansson
-
Allow both
current_page?(url_hash)andcurrent_page?(**url_hash)on Ruby 2.7.Ryuta Kamizono
Action Pack
-
Ignore file fixtures on
db:fixtures:loadKevin Sjöberg
-
Fix ActionController::Live controller test deadlocks by removing the body buffer size limit for tests.
Dylan Thacker-Smith
-
Correctly place optional path parameter booleans.
Previously, if you specify a url parameter that is part of the path as false it would include that part of the path as parameter for example:
get "(/optional/:optional_id)/things" => "foo#foo", as: :things things_path(optional_id: false) # => /things?optional_id=falseAfter this change, true and false will be treated the same when used as optional path parameters. Meaning now:
get '(this/:my_bool)/that' as: :that that_path(my_bool: true) # => `/this/true/that` that_path(my_bool: false) # => `/this/false/that`Adam Hess
-
Add support for 'private, no-store' Cache-Control headers.
Previously, 'no-store' was exclusive; no other directives could be specified.
Alex Smith
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
-
Fix
ArgumentErrorwith ruby 3.0 onRemoteConnection#disconnect.Vladislav
Active Storage
-
The parameters sent to
ffmpegfor generating a video preview image are now configurable underconfig.active_storage.video_preview_arguments.Brendon Muir
-
Fix Active Storage update task when running in an engine.
Justin Malčić*
-
Don't raise an error if the mime type is not recognized.
Fixes #41777.
Alex Ghiculescu
-
ActiveStorage::PreviewErroris raised when a previewer is unable to generate a preview image.Alex Robbin
-
respond with 404 given invalid variation key when asking for representations.
George Claghorn
-
Blobcreation shouldn't crash if no service selected.Alex Ghiculescu
Action Mailbox
- No changes.
Action Text
-
Always render attachment partials as HTML with
:htmlformat inside trix editor.James Brooks
Railties
-
Fix compatibility with
psych >= 4.Starting in Psych 4.0.0
YAML.loadbehaves likeYAML.safe_load. To preserve compatibilityRails.application.config_fornow usesYAML.unsafe_loadif available.Jean Boussier
-
Ensure
Rails.application.config_foralways cast hashes toActiveSupport::OrderedOptions.Jean Boussier
-
Fix create migration generator with
--pretendoption.euxx
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Fix the MySQL adapter to always set the right collation and charset to the connection session.
Rafael Mendonça França
-
Fix MySQL adapter handling of time objects when prepared statements are enabled.
Rafael Mendonça França
-
Fix scoping in enum fields using conditions that would generate an
INclause.Ryuta Kamizono
-
Skip optimised #exist? query when #include? is called on a relation with a having clause
Relations that have aliased select values AND a having clause that references an aliased select value would generate an error when #include? was called, due to an optimisation that would generate call #exists? on the relation instead, which effectively alters the select values of the query (and thus removes the aliased select values), but leaves the having clause intact. Because the having clause is then referencing an aliased column that is no longer present in the simplified query, an ActiveRecord::InvalidStatement error was raised.
An sample query affected by this problem:
Author.select('COUNT(*) as total_posts', 'authors.*') .joins(:posts) .group(:id) .having('total_posts > 2') .include?(Author.first)This change adds an addition check to the condition that skips the simplified #exists? query, which simply checks for the presence of a having clause.
Fixes #41417
Michael Smart
-
Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted without Rails knowledge (e.g., if app gets kill -9d during long-running query or due to Rack::Timeout), app won't end up in perpetual crash state for being inconsistent with Postgres.
wbharding, Martin Tepper
Action View
- No changes.
Action Pack
-
Re-define routes when not set correctly via inheritance.
John Hawthorn
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Active Support
-
ActiveSupport::Cache::MemCacheStorenow accepts an explicitnilfor itsaddressesargument.config.cache_store = :mem_cache_store, nil # is now equivalent to config.cache_store = :mem_cache_store # and is also equivalent to config.cache_store = :mem_cache_store, ENV["MEMCACHE_SERVERS"] || "localhost:11211" # which is the fallback behavior of DalliThis helps those migrating from
:dalli_store, where an explicitnilwas permitted.Michael Overmeyer
Active Model
- No changes.
Active Record
-
Fix timestamp type for sqlite3.
Eileen M. Uchitelle
-
Make destroy async transactional.
An active record rollback could occur while enqueuing a job. In this case the job would enqueue even though the database deletion rolledback putting things in a funky state.
Now the jobs are only enqueued until after the db transaction has been committed.
Cory Gwin
-
Fix malformed packet error in MySQL statement for connection configuration.
robinroestenburg
-
Connection specification now passes the "url" key as a configuration for the adapter if the "url" protocol is "jdbc", "http", or "https". Previously only urls with the "jdbc" prefix were passed to the Active Record Adapter, others are assumed to be adapter specification urls.
Fixes #41137.
Jonathan Bracy
-
Fix granular connection swapping when there are multiple abstract classes.
Eileen M. Uchitelle
-
Fix
find_bywith custom primary key for belongs_to association.Ryuta Kamizono
-
Add support for
rails console --sandboxfor multiple database applications.alpaca-tc
-
Fix
whereon polymorphic association with empty array.Ryuta Kamizono
-
Fix preventing writes for
ApplicationRecord.Eileen M. Uchitelle
Action View
- No changes.
Action Pack
-
Fix error in
ActionController::LogSubscriberthat would happen when throwing inside a controller action.Janko Marohnić
-
Fix
fixture_file_uploaddeprecation whenfile_fixture_pathis a relative path.Eugene Kenny
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Active Support
-
Change
IPAddr#to_jsonto match the behavior of the json gem returning the string representation instead of the instance variables of the object.Before:
IPAddr.new("127.0.0.1").to_json # => "{\"addr\":2130706433,\"family\":2,\"mask_addr\":4294967295}"After:
IPAddr.new("127.0.0.1").to_json # => "\"127.0.0.1\""
Active Model
- No changes.
Active Record
-
Fix fixtures loading when strict loading is enabled for the association.
Alex Ghiculescu
-
Fix
wherewith custom primary key for belongs_to association.Ryuta Kamizono
-
Fix
wherewith aliased associations.Ryuta Kamizono
-
Fix
composed_ofwith symbol mapping.Ryuta Kamizono
-
Don't skip money's type cast for pluck and calculations.
Ryuta Kamizono
-
Fix
whereon polymorphic association with non Active Record object.Ryuta Kamizono
-
Make sure
db:prepareworks even the schema file doesn't exist.Rafael Mendonça França
-
Fix complicated
has_many :throughwith nested where condition.Ryuta Kamizono
-
Handle STI models for
has_many dependent: :destroy_async.Muhammad Usman
-
Restore possibility of passing
falseto :polymorphic option ofbelongs_to.Previously, passing
falsewould trigger the option validation logic to throw an error saying :polymorphic would not be a valid option.glaszig
-
Allow adding nonnamed expression indexes to be revertible.
Fixes #40732.
Previously, the following code would raise an error, when executed while rolling back, and the index name should be specified explicitly. Now, the index name is inferred automatically.
add_index(:items, "to_tsvector('english', description)")fatkodima
Action View
-
Fix lazy translation in partial with block.
Marek Kasztelnik
-
Avoid extra
SELECT COUNTqueries when rendering Active Record collections.aar0nr
-
Link preloading keep integrity hashes in the header.
Étienne Barrié
-
Add
config.action_view.preload_links_headerto allow disabling of theLinkheader being added by default when usingstylesheet_link_tagandjavascript_include_tag.Andrew White
-
The
translatehelper now resolvesdefaultvalues when anilkey is specified, instead of always returningnil.Jonathan Hefner
Action Pack
-
Fix nil translation key lookup in controllers/
Jan Klimo
-
Quietly handle unknown HTTP methods in Action Dispatch SSL middleware.
Alex Robbin
-
Change the request method to a
GETwhen passing failed requests down toconfig.exceptions_app.Alex Robbin
Active Job
-
Make
retry_jobreturn the job that was created.Rafael Mendonça França
-
Include
ActiveSupport::Testing::AssertionsinActiveJob::TestHelpers.Mikkel Malmberg
Action Mailer
-
Sets default mailer queue to
"default"in the mail assertions.Paul Keen
Action Cable
- No changes.
Active Storage
-
Fix S3 multipart uploads when threshold is larger than file.
Matt Muller
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Allow spaces in path to Yarn binstub and only run on precompile if needed.
Markus Doits
-
Populate ARGV for app template.
Fixes #40945.
Jonathan Hefner
Active Support
-
Ensure
MemoryStoredisables compression by default. Reverts behavior ofMemoryStoreto its prior rails5.1behavior.Max Gurewitz
-
Calling
iso8601on negative durations retains the negative sign on individual digits instead of prepending it.This change is required so we can interoperate with PostgreSQL, which prefers negative signs for each component.
Compatibility with other iso8601 parsers which support leading negatives as well as negatives per component is still retained.
Before:
(-1.year - 1.day).iso8601 # => "-P1Y1D"After:
(-1.year - 1.day).iso8601 # => "P-1Y-1D"Vipul A M
-
Remove deprecated
ActiveSupport::Notifications::Instrumenter#end=.Rafael Mendonça França
-
Deprecate
ActiveSupport::Multibyte::Unicode.default_normalization_form.Rafael Mendonça França
-
Remove deprecated
ActiveSupport::Multibyte::Unicode.pack_graphemes,ActiveSupport::Multibyte::Unicode.unpack_graphemes,ActiveSupport::Multibyte::Unicode.normalize,ActiveSupport::Multibyte::Unicode.downcase,ActiveSupport::Multibyte::Unicode.upcaseandActiveSupport::Multibyte::Unicode.swapcase.Rafael Mendonça França
-
Remove deprecated
ActiveSupport::Multibyte::Chars#consumes?andActiveSupport::Multibyte::Chars#normalize.Rafael Mendonça França
-
Remove deprecated file
active_support/core_ext/range/include_range.Rafael Mendonça França
-
Remove deprecated file
active_support/core_ext/hash/transform_values.Rafael Mendonça França
-
Remove deprecated file
active_support/core_ext/hash/compact.Rafael Mendonça França
-
Remove deprecated file
active_support/core_ext/array/prepend_and_append.Rafael Mendonça França
-
Remove deprecated file
active_support/core_ext/numeric/inquiry.Rafael Mendonça França
-
Remove deprecated file
active_support/core_ext/module/reachable.Rafael Mendonça França
-
Remove deprecated
Module#parent_name,Module#parentandModule#parents.Rafael Mendonça França
-
Remove deprecated
ActiveSupport::LoggerThreadSafeLevel#after_initialize.Rafael Mendonça França
-
Remove deprecated
LoggerSilenceconstant.Rafael Mendonça França
-
Remove deprecated fallback to
I18n.default_localwhenconfig.i18n.fallbacksis empty.Rafael Mendonça França
-
Remove entries from local cache on
RedisCacheStore#delete_matchedFixes #38627
ojab
-
Speed up
ActiveSupport::SecurityUtils.fixed_length_secure_compareby usingOpenSSL.fixed_length_secure_compare, if available.Nate Matykiewicz
-
ActiveSupport::Cache::MemCacheStorenow checksENV["MEMCACHE_SERVERS"]before falling back to"localhost:11211"if configured without any addresses.config.cache_store = :mem_cache_store # is now equivalent to config.cache_store = :mem_cache_store, ENV["MEMCACHE_SERVERS"] || "localhost:11211" # instead of config.cache_store = :mem_cache_store, "localhost:11211" # ignores ENV["MEMCACHE_SERVERS"]Sam Bostock
-
ActiveSupport::Subscriber#attach_tonow accepts aninherit_all:argument. When set to true, it allows a subscriber to receive events for methods defined in the subscriber's ancestor class(es).class ActionControllerSubscriber < ActiveSupport::Subscriber attach_to :action_controller def start_processing(event) info "Processing by #{event.payload[:controller]}##{event.payload[:action]} as #{format}" end def redirect_to(event) info { "Redirected to #{event.payload[:location]}" } end end # We detach ActionControllerSubscriber from the :action_controller namespace so that our CustomActionControllerSubscriber # can provide its own instrumentation for certain events in the namespace ActionControllerSubscriber.detach_from(:action_controller) class CustomActionControllerSubscriber < ActionControllerSubscriber attach_to :action_controller, inherit_all: true def start_processing(event) info "A custom response to start_processing events" end # => CustomActionControllerSubscriber will process events for "start_processing.action_controller" notifications # using its own #start_processing implementation, while retaining ActionControllerSubscriber's instrumentation # for "redirect_to.action_controller" notifications endAdrianna Chang
-
Allow the digest class used to generate non-sensitive digests to be configured with
config.active_support.hash_digest_class.config.active_support.use_sha1_digestsis deprecated in favour ofconfig.active_support.hash_digest_class = ::Digest::SHA1.Dirkjan Bussink
-
Fix bug to make memcached write_entry expire correctly with unless_exist
Jye Lee
-
Add
ActiveSupport::Durationconversion methodsin_seconds,in_minutes,in_hours,in_days,in_weeks,in_months, andin_yearsreturn the respective duration covered.Jason York
-
Fixed issue in
ActiveSupport::Cache::RedisCacheStorenot passing options toread_multicausingfetch_multito not work properlyRajesh Sharma
-
Fixed issue in
ActiveSupport::Cache::MemCacheStorewhich caused duplicate compression, and caused the providedcompression_thresholdto not be respected.Max Gurewitz
-
Prevent
RedisCacheStoreandMemCacheStorefrom performing compression when reading entries written withraw: true.Max Gurewitz
-
URI.parseris deprecated and will be removed in Rails 6.2. UseURI::DEFAULT_PARSERinstead.Jean Boussier
-
require_dependencyhas been documented to be obsolete in:zeitwerkmode. The method is not deprecated as such (yet), but applications are encouraged to not use it.In
:zeitwerkmode, semantics match Ruby's and you do not need to be defensive with load order. Just refer to classes and modules normally. If the constant name is dynamic, camelize if needed, and constantize.Xavier Noria
-
Add 3rd person aliases of
Symbol#start_with?andSymbol#end_with?.:foo.starts_with?("f") # => true :foo.ends_with?("o") # => trueRyuta Kamizono
-
Add override of unary plus for
ActiveSupport::Duration.+ 1.secondis now identical to+1.secondto prevent errors where a seemingly innocent change of formatting leads to a change in the code behavior.Before:
+1.second.class # => ActiveSupport::Duration (+ 1.second).class # => IntegerAfter:
+1.second.class # => ActiveSupport::Duration (+ 1.second).class # => ActiveSupport::DurationFixes #39079.
Roman Kushnir
-
Add subsec to
ActiveSupport::TimeWithZone#inspect.Before:
Time.at(1498099140).in_time_zone.inspect # => "Thu, 22 Jun 2017 02:39:00 UTC +00:00" Time.at(1498099140, 123456780, :nsec).in_time_zone.inspect # => "Thu, 22 Jun 2017 02:39:00 UTC +00:00" Time.at(1498099140 + Rational("1/3")).in_time_zone.inspect # => "Thu, 22 Jun 2017 02:39:00 UTC +00:00"After:
Time.at(1498099140).in_time_zone.inspect # => "Thu, 22 Jun 2017 02:39:00.000000000 UTC +00:00" Time.at(1498099140, 123456780, :nsec).in_time_zone.inspect # => "Thu, 22 Jun 2017 02:39:00.123456780 UTC +00:00" Time.at(1498099140 + Rational("1/3")).in_time_zone.inspect # => "Thu, 22 Jun 2017 02:39:00.333333333 UTC +00:00"akinomaeni
-
Calling
ActiveSupport::TaggedLogging#taggedwithout a block now returns a tagged logger.logger.tagged("BCX").info("Funky time!") # => [BCX] Funky time!Eugene Kenny
-
Align
Range#cover?extension behavior with Ruby behavior for backwards ranges.(1..10).cover?(5..3)now returnsfalse, as it does in plain Ruby.Also update
#include?and#===behavior to match.Michael Groeneman
-
Update to TZInfo v2.0.0.
This changes the output of
ActiveSupport::TimeZone.utc_to_local, but can be controlled with theActiveSupport.utc_to_local_returns_utc_offset_timesconfig.New Rails 6.1 apps have it enabled by default, existing apps can upgrade via the config in config/initializers/new_framework_defaults_6_1.rb
See the
utc_to_local_returns_utc_offset_timesdocumentation for details.Phil Ross, Jared Beck
-
Add Date and Time
#yesterday?and#tomorrow?alongside#today?.Aliased to
#prev_day?and#next_day?to match the existing#prev/next_daymethods.Jatin Dhankhar
-
Add
Enumerable#pickto complementActiveRecord::Relation#pick.Eugene Kenny
-
[Breaking change]
ActiveSupport::Callbacks#halted_callback_hooknow receive a 2nd argument:ActiveSupport::Callbacks#halted_callback_hooknow receive the name of the callback being halted as second argument. This change will allow you to differentiate which callbacks halted the chain and act accordingly.class Book < ApplicationRecord before_save { throw(:abort) } before_create { throw(:abort) } def halted_callback_hook(filter, callback_name) Rails.logger.info("Book couldn't be #{callback_name}d") end Book.create # => "Book couldn't be created" book.save # => "Book couldn't be saved" endEdouard Chin
-
Support
prependwithActiveSupport::Concern.Allows a module with
extend ActiveSupport::Concernto be prepended.module Imposter extend ActiveSupport::Concern # Same as `included`, except only run when prepended. prepended do end end class Person prepend Imposter endClass methods are prepended to the base class, concerning is also updated:
concerning :Imposter, prepend: true do.Jason Karns, Elia Schito
-
Deprecate using
Range#include?method to check the inclusion of a value in a date time range. It is recommended to useRange#cover?method instead ofRange#include?to check the inclusion of a value in a date time range.Vishal Telangre
-
Support added for a
round_modeparameter, in all number helpers. (See:BigDecimal::mode.)number_to_currency(1234567890.50, precision: 0, round_mode: :half_down) # => "$1,234,567,890" number_to_percentage(302.24398923423, precision: 5, round_mode: :down) # => "302.24398%" number_to_rounded(389.32314, precision: 0, round_mode: :ceil) # => "390" number_to_human_size(483989, precision: 2, round_mode: :up) # => "480 KB" number_to_human(489939, precision: 2, round_mode: :floor) # => "480 Thousand" 485000.to_s(:human, precision: 2, round_mode: :half_even) # => "480 Thousand"Tom Lord
-
Array#to_sentenceno longer returns a frozen string.Before:
['one', 'two'].to_sentence.frozen? # => trueAfter:
['one', 'two'].to_sentence.frozen? # => falseNicolas Dular
-
When an instance of
ActiveSupport::Durationis converted to aniso8601duration string, ifweeksare mixed withdateparts, theweekpart will be converted to days. This keeps the parser and serializer on the same page.duration = ActiveSupport::Duration.build(1000000) # 1 week, 4 days, 13 hours, 46 minutes, and 40.0 seconds duration_iso = duration.iso8601 # P11DT13H46M40S ActiveSupport::Duration.parse(duration_iso) # 11 days, 13 hours, 46 minutes, and 40 seconds duration = ActiveSupport::Duration.build(604800) # 1 week duration_iso = duration.iso8601 # P1W ActiveSupport::Duration.parse(duration_iso) # 1 weekAbhishek Sarkar
-
Add block support to
ActiveSupport::Testing::TimeHelpers#travel_back.Tim Masliuchenko
-
Update
ActiveSupport::Messages::Metadata#fresh?to work for cookies with expiry set whenActiveSupport.parse_json_times = true.Christian Gregg
-
Support symbolic links for
content_pathinActiveSupport::EncryptedFile.Takumi Shotoku
-
Improve
Range#===,Range#include?, andRange#cover?to work with beginless (startless) and endless range targets.Allen Hsu, Andrew Hodgkinson
-
Don't use
Process#clock_gettime(CLOCK_THREAD_CPUTIME_ID)on Solaris.Iain Beeston
-
Prevent
ActiveSupport::Duration.build(value)from creating instances ofActiveSupport::Durationunlessvalueis of typeNumeric.Addresses the errant set of behaviours described in #37012 where
ActiveSupport::Durationcomparisons would fail confusingly or return unexpected results when comparing durations built from instances ofString.Before:
small_duration_from_string = ActiveSupport::Duration.build('9') large_duration_from_string = ActiveSupport::Duration.build('100000000000000') small_duration_from_int = ActiveSupport::Duration.build(9) large_duration_from_string > small_duration_from_string # => false small_duration_from_string == small_duration_from_int # => false small_duration_from_int < large_duration_from_string # => ArgumentError (comparison of ActiveSupport::Duration::Scalar with ActiveSupport::Duration failed) large_duration_from_string > small_duration_from_int # => ArgumentError (comparison of String with ActiveSupport::Duration failed)After:
small_duration_from_string = ActiveSupport::Duration.build('9') # => TypeError (can't build an ActiveSupport::Duration from a String)Alexei Emam
-
Add
ActiveSupport::Cache::Store#delete_multimethod to delete multiple keys from the cache store.Peter Zhu
-
Support multiple arguments in
HashWithIndifferentAccessformergeandupdatemethods, to follow Ruby 2.6 addition.Wojciech Wnętrzak
-
Allow initializing
thread_mattr_*attributes via:defaultoption.class Scraper thread_mattr_reader :client, default: Api::Client.new endGuilherme Mansur
-
Add
compact_blankfor those times when you want to remove #blank? values from an Enumerable (alsocompact_blank!on Hash, Array, ActionController::Parameters).Dana Sherson
-
Make ActiveSupport::Logger Fiber-safe.
Use
Fiber.current.__id__inActiveSupport::Logger#local_level=in order to make log level local to Ruby Fibers in addition to Threads.Example:
logger = ActiveSupport::Logger.new(STDOUT) logger.level = 1 puts "Main is debug? #{logger.debug?}" Fiber.new { logger.local_level = 0 puts "Thread is debug? #{logger.debug?}" }.resume puts "Main is debug? #{logger.debug?}"Before:
Main is debug? false Thread is debug? true Main is debug? trueAfter:
Main is debug? false Thread is debug? true Main is debug? falseFixes #36752.
Alexander Varnin
-
Allow the
on_rotationproc used when decrypting/verifying a message to be passed at the constructor level.Before:
crypt = ActiveSupport::MessageEncryptor.new('long_secret') crypt.decrypt_and_verify(encrypted_message, on_rotation: proc { ... }) crypt.decrypt_and_verify(another_encrypted_message, on_rotation: proc { ... })After:
crypt = ActiveSupport::MessageEncryptor.new('long_secret', on_rotation: proc { ... }) crypt.decrypt_and_verify(encrypted_message) crypt.decrypt_and_verify(another_encrypted_message)Edouard Chin
-
delegate_missing_towould raise aDelegationErrorif the object delegated to wasnil. Now theallow_niloption has been added to enable the user to specify they wantnilreturned in this case.Matthew Tanous
-
truncatewould return the original string if it was too short to be truncated and a frozen string if it were long enough to be truncated. Now truncate will consistently return an unfrozen string regardless. This behavior is consistent withgsubandstrip.Before:
'foobar'.truncate(5).frozen? # => true 'foobar'.truncate(6).frozen? # => falseAfter:
'foobar'.truncate(5).frozen? # => false 'foobar'.truncate(6).frozen? # => falseJordan Thomas
Active Model
-
Pass in
baseinstead ofbase_classto Error.human_attribute_nameThis is useful in cases where the
human_attribute_namemethod depends on other attributes' values of the class under validation to derive what the attribute name should be.Filipe Sabella
-
Deprecate marshalling load from legacy attributes format.
Ryuta Kamizono
-
*_previously_changed?accepts:fromand:tokeyword arguments like*_changed?.topic.update!(status: :archived) topic.status_previously_changed?(from: "active", to: "archived") # => trueGeorge Claghorn
-
Raise FrozenError when trying to write attributes that aren't backed by the database on an object that is frozen:
class Animal include ActiveModel::Attributes attribute :age end animal = Animal.new animal.freeze animal.age = 25 # => FrozenError, "can't modify a frozen Animal"Josh Brody
-
Add
*_previously_wasattribute methods when dirty tracking. Example:pirate.update(catchphrase: "Ahoy!") pirate.previous_changes["catchphrase"] # => ["Thar She Blows!", "Ahoy!"] pirate.catchphrase_previously_was # => "Thar She Blows!"DHH
-
Encapsulate each validation error as an Error object.
The
ActiveModel’serrorscollection is now an array of these Error objects, instead of messages/details hash.For each of these
Errorobject, itsmessageandfull_messagemethods are for generating error messages. Itsdetailsmethod would return error’s extra parameters, found in the originaldetailshash.The change tries its best at maintaining backward compatibility, however some edge cases won’t be covered, like
errors#firstwill returnActiveModel::Errorand manipulatingerrors.messagesanderrors.detailshashes directly will have no effect. Moving forward, please convert those direct manipulations to use provided API methods instead.The list of deprecated methods and their planned future behavioral changes at the next major release are:
errors#slice!will be removed.errors#eachwith thekey, valuetwo-arguments block will stop working, while theerrorsingle-argument block would returnErrorobject.errors#valueswill be removed.errors#keyswill be removed.errors#to_xmlwill be removed.errors#to_hwill be removed, and can be replaced witherrors#to_hash.- Manipulating
errorsitself as a hash will have no effect (e.g.errors[:foo] = 'bar'). - Manipulating the hash returned by
errors#messages(e.g.errors.messages[:foo] = 'bar') will have no effect. - Manipulating the hash returned by
errors#details(e.g.errors.details[:foo].clear) will have no effect.
lulalala
Active Record
-
Only warn about negative enums if a positive form that would cause conflicts exists.
Fixes #39065.
Alex Ghiculescu
-
Change
attribute_for_inspectto takefilter_attributesin consideration.Rafael Mendonça França
-
Fix odd behavior of inverse_of with multiple belongs_to to same class.
Fixes #35204.
Tomoyuki Kai
-
Build predicate conditions with objects that delegate
#idand primary key:class AdminAuthor delegate_missing_to :@author def initialize(author) @author = author end end Post.where(author: AdminAuthor.new(author))Sean Doyle
-
Add
connected_to_manyAPI.This API allows applications to connect to multiple databases at once without switching all of them or implementing a deeply nested stack.
Before:
AnimalsRecord.connected_to(role: :reading) do MealsRecord.connected_to(role: :reading) do Dog.first # read from animals replica Dinner.first # read from meals replica Person.first # read from primary writer end end
After:
ActiveRecord::Base.connected_to_many([AnimalsRecord, MealsRecord], role: :reading) do Dog.first # read from animals replica Dinner.first # read from meals replica Person.first # read from primary writer end
Eileen M. Uchitelle, John Crepezzi
-
Add option to raise or log for
ActiveRecord::StrictLoadingViolationError.Some applications may not want to raise an error in production if using
strict_loading. This would allow an application to set strict loading to log for the production environment while still raising in development and test environments.Set
config.active_record.action_on_strict_loading_violationto:logerrors instead of raising.Eileen M. Uchitelle
-
Allow the inverse of a
has_oneassociation that was previously autosaved to be loaded.Fixes #34255.
Steven Weber
-
Optimise the length of index names for polymorphic references by using the reference name rather than the type and id column names.
Because the default behaviour when adding an index with multiple columns is to use all column names in the index name, this could frequently lead to overly long index names for polymorphic references which would fail the migration if it exceeded the database limit.
This change reduces the chance of that happening by using the reference name, e.g.
index_my_table_on_my_reference.Fixes #38655.
Luke Redpath
-
MySQL: Uniqueness validator now respects default database collation, no longer enforce case sensitive comparison by default.
Ryuta Kamizono
-
Remove deprecated methods from
ActiveRecord::ConnectionAdapters::DatabaseLimits.column_name_lengthtable_name_lengthcolumns_per_tableindexes_per_tablecolumns_per_multicolumn_indexsql_query_lengthjoins_per_queryRafael Mendonça França
-
Remove deprecated
ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_multi_insert?.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_foreign_keys_in_create?.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#supports_ranges?.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base#update_attributesandActiveRecord::Base#update_attributes!.Rafael Mendonça França
-
Remove deprecated
migrations_pathargument inActiveRecord::ConnectionAdapter::SchemaStatements#assume_migrated_upto_version.Rafael Mendonça França
-
Remove deprecated
config.active_record.sqlite3.represent_boolean_as_integer.Rafael Mendonça França
-
relation.createdoes no longer leak scope to class level querying methods in initialization block and callbacks.Before:
User.where(name: "John").create do |john| User.find_by(name: "David") # => nil endAfter:
User.where(name: "John").create do |john| User.find_by(name: "David") # => #<User name: "David", ...> endRyuta Kamizono
-
Named scope chain does no longer leak scope to class level querying methods.
class User < ActiveRecord::Base scope :david, -> { User.where(name: "David") } endBefore:
User.where(name: "John").david # SELECT * FROM users WHERE name = 'John' AND name = 'David'After:
User.where(name: "John").david # SELECT * FROM users WHERE name = 'David'Ryuta Kamizono
-
Remove deprecated methods from
ActiveRecord::DatabaseConfigurations.fetcheachfirstvalues[]=Rafael Mendonça França
-
where.notnow generates NAND predicates instead of NOR.Before:
User.where.not(name: "Jon", role: "admin") # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'After:
User.where.not(name: "Jon", role: "admin") # SELECT * FROM users WHERE NOT (name == 'Jon' AND role == 'admin')Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Result#to_hashmethod.Rafael Mendonça França
-
Deprecate
ActiveRecord::Base.allow_unsafe_raw_sql.Rafael Mendonça França
-
Remove deprecated support for using unsafe raw SQL in
ActiveRecord::Relationmethods.Rafael Mendonça França
-
Allow users to silence the "Rails couldn't infer whether you are using multiple databases..." message using
config.active_record.suppress_multiple_database_warning.Omri Gabay
-
Connections can be granularly switched for abstract classes when
connected_tois called.This change allows
connected_toto switch aroleand/orshardfor a single abstract class instead of all classes globally. Applications that want to use the new feature need to setconfig.active_record.legacy_connection_handlingtofalsein their application configuration.Example usage:
Given an application we have a
Usermodel that inherits fromApplicationRecordand aDogmodel that inherits fromAnimalsRecord.AnimalsRecordandApplicationRecordhave writing and reading connections as well as sharddefault,one, andtwo.ActiveRecord::Base.connected_to(role: :reading) do User.first # reads from default replica Dog.first # reads from default replica AnimalsRecord.connected_to(role: :writing, shard: :one) do User.first # reads from default replica Dog.first # reads from shard one primary end User.first # reads from default replica Dog.first # reads from default replica ApplicationRecord.connected_to(role: :writing, shard: :two) do User.first # reads from shard two primary Dog.first # reads from default replica end endEileen M. Uchitelle, John Crepezzi
-
Allow double-dash comment syntax when querying read-only databases
James Adam
-
Add
values_atmethod.Returns an array containing the values associated with the given methods.
topic = Topic.first topic.values_at(:title, :author_name) # => ["Budget", "Jason"]Similar to
Hash#values_atbut on an Active Record instance.Guillaume Briday
-
Fix
read_attribute_before_type_castto consider attribute aliases.Marcelo Lauxen
-
Support passing record to uniqueness validator
:conditionscallable:class Article < ApplicationRecord validates_uniqueness_of :title, conditions: ->(article) { published_at = article.published_at where(published_at: published_at.beginning_of_year..published_at.end_of_year) } endEliot Sykes
-
BatchEnumerator#update_allandBatchEnumerator#delete_allnow return the total number of rows affected, just like their non-batched counterparts.Person.in_batches.update_all("first_name = 'Eugene'") # => 42 Person.in_batches.delete_all # => 42Fixes #40287.
Eugene Kenny
-
Add support for PostgreSQL
intervaldata type with conversion toActiveSupport::Durationwhen loading records from database and serialization to ISO 8601 formatted duration string on save. Add support to define a column in migrations and get it in a schema dump. Optional column precision is supported.To use this in 6.1, you need to place the next string to your model file:
attribute :duration, :intervalTo keep old behavior until 6.2 is released:
attribute :duration, :stringExample:
create_table :events do |t| t.string :name t.interval :duration end class Event < ApplicationRecord attribute :duration, :interval end Event.create!(name: 'Rock Fest', duration: 2.days) Event.last.duration # => 2 days Event.last.duration.iso8601 # => "P2D" Event.new(duration: 'P1DT12H3S').duration # => 1 day, 12 hours, and 3 seconds Event.new(duration: '1 day') # Unknown value will be ignored and NULL will be written to databaseAndrey Novikov
-
Allow associations supporting the
dependent:key to takedependent: :destroy_async.class Account < ActiveRecord::Base belongs_to :supplier, dependent: :destroy_async end:destroy_asyncwill enqueue a job to destroy associated records in the background.DHH, George Claghorn, Cory Gwin, Rafael Mendonça França, Adrianna Chang
-
Add
SKIP_TEST_DATABASEenvironment variable to disable modifying the test database whenrails db:createandrails db:dropare called.Jason Schweier
-
connects_tocan only be called onActiveRecord::Baseor abstract classes.Ensure that
connects_tocan only be called fromActiveRecord::Baseor abstract classes. This protects the application from opening duplicate or too many connections.Eileen M. Uchitelle, John Crepezzi
-
All connection adapters
executenow raisesActiveRecord::ConnectionNotEstablishedrather thanActiveRecord::StatementInvalidwhen they encounter a connection error.Jean Boussier
-
Mysql2Adapter#quote_stringnow raisesActiveRecord::ConnectionNotEstablishedrather thanActiveRecord::StatementInvalidwhen it can't connect to the MySQL server.Jean Boussier
-
Add support for check constraints that are
NOT VALIDviavalidate: false(PostgreSQL-only).Alex Robbin
-
Ensure the default configuration is considered primary or first for an environment
If a multiple database application provides a configuration named primary, that will be treated as default. In applications that do not have a primary entry, the default database configuration will be the first configuration for an environment.
Eileen M. Uchitelle
-
Allow
wherereferences association names as joined table name aliases.class Comment < ActiveRecord::Base enum label: [:default, :child] has_many :children, class_name: "Comment", foreign_key: :parent_id end # ... FROM comments LEFT OUTER JOIN comments children ON ... WHERE children.label = 1 Comment.includes(:children).where("children.label": "child")Ryuta Kamizono
-
Support storing demodulized class name for polymorphic type.
Before Rails 6.1, storing demodulized class name is supported only for STI type by
store_full_sti_classclass attribute.Now
store_full_class_nameclass attribute can handle both STI and polymorphic types.Ryuta Kamizono
-
Deprecate
rails db:structure:{load, dump}tasks and extendrails db:schema:{load, dump}tasks to work with either:rubyor:sqlformat, depending onconfig.active_record.schema_formatconfiguration value.fatkodima
-
Respect the
selectvalues for eager loading.post = Post.select("UPPER(title) AS title").first post.title # => "WELCOME TO THE WEBLOG" post.body # => ActiveModel::MissingAttributeError # Rails 6.0 (ignore the `select` values) post = Post.select("UPPER(title) AS title").eager_load(:comments).first post.title # => "Welcome to the weblog" post.body # => "Such a lovely day" # Rails 6.1 (respect the `select` values) post = Post.select("UPPER(title) AS title").eager_load(:comments).first post.title # => "WELCOME TO THE WEBLOG" post.body # => ActiveModel::MissingAttributeErrorRyuta Kamizono
-
Allow attribute's default to be configured but keeping its own type.
class Post < ActiveRecord::Base attribute :written_at, default: -> { Time.now.utc } end # Rails 6.0 Post.type_for_attribute(:written_at) # => #<Type::Value ... precision: nil, ...> # Rails 6.1 Post.type_for_attribute(:written_at) # => #<Type::DateTime ... precision: 6, ...>Ryuta Kamizono
-
Allow default to be configured for Enum.
class Book < ActiveRecord::Base enum status: [:proposed, :written, :published], _default: :published end Book.new.status # => "published"Ryuta Kamizono
-
Deprecate YAML loading from legacy format older than Rails 5.0.
Ryuta Kamizono
-
Added the setting
ActiveRecord::Base.immutable_strings_by_default, which allows you to specify that all string columns should be frozen unless otherwise specified. This will reduce memory pressure for applications which do not generally mutate string properties of Active Record objects.Sean Griffin, Ryuta Kamizono
-
Deprecate
map!andcollect!onActiveRecord::Result.Ryuta Kamizono
-
Support
relation.andfor intersection as Set theory.david_and_mary = Author.where(id: [david, mary]) mary_and_bob = Author.where(id: [mary, bob]) david_and_mary.merge(mary_and_bob) # => [mary, bob] david_and_mary.and(mary_and_bob) # => [mary] david_and_mary.or(mary_and_bob) # => [david, mary, bob]Ryuta Kamizono
-
Merging conditions on the same column no longer maintain both conditions, and will be consistently replaced by the latter condition in Rails 6.2. To migrate to Rails 6.2's behavior, use
relation.merge(other, rewhere: true).# Rails 6.1 (IN clause is replaced by merger side equality condition) Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob] # Rails 6.1 (both conflict conditions exists, deprecated) Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [] # Rails 6.1 with rewhere to migrate to Rails 6.2's behavior Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob] # Rails 6.2 (same behavior with IN clause, mergee side condition is consistently replaced) Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob] Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]Ryuta Kamizono
-
Do not mark Postgresql MAC address and UUID attributes as changed when the assigned value only varies by case.
Peter Fry
-
Resolve issue with insert_all unique_by option when used with expression index.
When the
:unique_byoption ofActiveRecord::Persistence.insert_allandActiveRecord::Persistence.upsert_allwas used with the name of an expression index, an error was raised. Adding a guard around the formatting behavior for the:unique_bycorrects this.Usage:
create_table :books, id: :integer, force: true do |t| t.column :name, :string t.index "lower(name)", unique: true end Book.insert_all [{ name: "MyTest" }], unique_by: :index_books_on_lower_nameFixes #39516.
Austen Madden
-
Add basic support for CHECK constraints to database migrations.
Usage:
add_check_constraint :products, "price > 0", name: "price_check" remove_check_constraint :products, name: "price_check"fatkodima
-
Add
ActiveRecord::Base.strict_loading_by_defaultandActiveRecord::Base.strict_loading_by_default=to enable/disable strict_loading mode by default for a model. The configuration's value is inheritable by subclasses, but they can override that value and it will not impact parent class.Usage:
class Developer < ApplicationRecord self.strict_loading_by_default = true has_many :projects end dev = Developer.first dev.projects.first # => ActiveRecord::StrictLoadingViolationError Exception: Developer is marked as strict_loading and Project cannot be lazily loaded.bogdanvlviv
-
Deprecate passing an Active Record object to
quote/type_castdirectly.Ryuta Kamizono
-
Default engine
ENGINE=InnoDBis no longer dumped to make schema more agnostic.Before:
create_table "accounts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t| endAfter:
create_table "accounts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t| endRyuta Kamizono
-
Added delegated type as an alternative to single-table inheritance for representing class hierarchies. See ActiveRecord::DelegatedType for the full description.
DHH
-
Deprecate aggregations with group by duplicated fields.
To migrate to Rails 6.2's behavior, use
uniq!(:group)to deduplicate group fields.accounts = Account.group(:firm_id) # duplicated group fields, deprecated. accounts.merge(accounts.where.not(credit_limit: nil)).sum(:credit_limit) # => { # [1, 1] => 50, # [2, 2] => 60 # } # use `uniq!(:group)` to deduplicate group fields. accounts.merge(accounts.where.not(credit_limit: nil)).uniq!(:group).sum(:credit_limit) # => { # 1 => 50, # 2 => 60 # }Ryuta Kamizono
-
Deprecate duplicated query annotations.
To migrate to Rails 6.2's behavior, use
uniq!(:annotate)to deduplicate query annotations.accounts = Account.where(id: [1, 2]).annotate("david and mary") # duplicated annotations, deprecated. accounts.merge(accounts.rewhere(id: 3)) # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */ /* david and mary */ # use `uniq!(:annotate)` to deduplicate annotations. accounts.merge(accounts.rewhere(id: 3)).uniq!(:annotate) # SELECT accounts.* FROM accounts WHERE accounts.id = 3 /* david and mary */Ryuta Kamizono
-
Resolve conflict between counter cache and optimistic locking.
Bump an Active Record instance's lock version after updating its counter cache. This avoids raising an unnecessary
ActiveRecord::StaleObjectErrorupon subsequent transactions by maintaining parity with the corresponding database record'slock_versioncolumn.Fixes #16449.
Aaron Lipman
-
Support merging option
:rewhereto allow mergee side condition to be replaced exactly.david_and_mary = Author.where(id: david.id..mary.id) # both conflict conditions exists david_and_mary.merge(Author.where(id: bob)) # => [] # mergee side condition is replaced by rewhere david_and_mary.merge(Author.rewhere(id: bob)) # => [bob] # mergee side condition is replaced by rewhere option david_and_mary.merge(Author.where(id: bob), rewhere: true) # => [bob]Ryuta Kamizono
-
Add support for finding records based on signed ids, which are tamper-proof, verified ids that can be set to expire and scoped with a purpose. This is particularly useful for things like password reset or email verification, where you want the bearer of the signed id to be able to interact with the underlying record, but usually only within a certain time period.
signed_id = User.first.signed_id expires_in: 15.minutes, purpose: :password_reset User.find_signed signed_id # => nil, since the purpose does not match travel 16.minutes User.find_signed signed_id, purpose: :password_reset # => nil, since the signed id has expired travel_back User.find_signed signed_id, purpose: :password_reset # => User.first User.find_signed! "bad data" # => ActiveSupport::MessageVerifier::InvalidSignatureDHH
-
Support
ALGORITHM = INSTANTDDL option for index operations on MySQL.Ryuta Kamizono
-
Fix index creation to preserve index comment in bulk change table on MySQL.
Ryuta Kamizono
-
Allow
unscopeto be aware of table name qualified values.It is possible to unscope only the column in the specified table.
posts = Post.joins(:comments).group(:"posts.hidden") posts = posts.where("posts.hidden": false, "comments.hidden": false) posts.count # => { false => 10 } # unscope both hidden columns posts.unscope(where: :hidden).count # => { false => 11, true => 1 } # unscope only comments.hidden column posts.unscope(where: :"comments.hidden").count # => { false => 11 }Ryuta Kamizono, Slava Korolev
-
Fix
rewhereto truly overwrite collided where clause by new where clause.steve = Person.find_by(name: "Steve") david = Author.find_by(name: "David") relation = Essay.where(writer: steve) # Before relation.rewhere(writer: david).to_a # => [] # After relation.rewhere(writer: david).to_a # => [david]Ryuta Kamizono
-
Inspect time attributes with subsec and time zone offset.
p Knot.create => #<Knot id: 1, created_at: "2016-05-05 01:29:47.116928000 +0000">akinomaeni, Jonathan Hefner
-
Deprecate passing a column to
type_cast.Ryuta Kamizono
-
Deprecate
in_clause_lengthandallowed_index_name_lengthinDatabaseLimits.Ryuta Kamizono
-
Support bulk insert/upsert on relation to preserve scope values.
Josef Šimánek, Ryuta Kamizono
-
Preserve column comment value on changing column name on MySQL.
Islam Taha
-
Add support for
if_existsoption for removing an index.The
remove_indexmethod can take anif_existsoption. If this is set to true an error won't be raised if the index doesn't exist.Eileen M. Uchitelle
-
Remove ibm_db, informix, mssql, oracle, and oracle12 Arel visitors which are not used in the code base.
Ryuta Kamizono
-
Prevent
build_associationfromtouchinga parent record if the record isn't persisted forhas_oneassociations.Fixes #38219.
Josh Brody
-
Add support for
if_not_existsoption for adding index.The
add_indexmethod respectsif_not_existsoption. If it is set to true index won't be added.Usage:
add_index :users, :account_id, if_not_exists: trueThe
if_not_existsoption passed tocreate_tablealso gets propagated to indexes created within that migration so that if table and its indexes exist then there is no attempt to create them again.Prathamesh Sonpatki
-
Add
ActiveRecord::Base#previously_new_record?to show if a record was new before the last save.Tom Ward
-
Support descending order for
find_each,find_in_batches, andin_batches.Batch processing methods allow you to work with the records in batches, greatly reducing memory consumption, but records are always batched from oldest id to newest.
This change allows reversing the order, batching from newest to oldest. This is useful when you need to process newer batches of records first.
Pass
order: :descto yield batches in descending order. The default remainsorder: :asc.Person.find_each(order: :desc) do |person| person.party_all_night! endAlexey Vasiliev
-
Fix
insert_allwith enum values.Fixes #38716.
Joel Blum
-
Add support for
db:rollback:namefor multiple database applications.Multiple database applications will now raise if
db:rollbackis call and recommend using thedb:rollback:[NAME]to rollback migrations.Eileen M. Uchitelle
-
Relation#picknow uses already loaded results instead of making another query.Eugene Kenny
-
Deprecate using
return,breakorthrowto exit a transaction block after writes.Dylan Thacker-Smith
-
Dump the schema or structure of a database when calling
db:migrate:name.In previous versions of Rails,
rails db:migratewould dump the schema of the database. In Rails 6, that holds true (rails db:migratedumps all databases' schemas), butrails db:migrate:namedoes not share that behavior.Going forward, calls to
rails db:migrate:namewill dump the schema (or structure) of the database being migrated.Kyle Thompson
-
Reset the
ActiveRecord::Baseconnection afterrails db:migrate:name.When
rails db:migratehas finished, it ensures theActiveRecord::Baseconnection is reset to its original configuration. Going forward,rails db:migrate:namewill have the same behavior.Kyle Thompson
-
Disallow calling
connected_toon subclasses ofActiveRecord::Base.Behavior has not changed here but the previous API could be misleading to people who thought it would switch connections for only that class.
connected_toswitches the context from which we are getting connections, not the connections themselves.Eileen M. Uchitelle, John Crepezzi
-
Add support for horizontal sharding to
connects_toandconnected_to.Applications can now connect to multiple shards and switch between their shards in an application. Note that the shard swapping is still a manual process as this change does not include an API for automatic shard swapping.
Usage:
Given the following configuration:
# config/database.yml production: primary: database: my_database primary_shard_one: database: my_database_shard_oneConnect to multiple shards:
class ApplicationRecord < ActiveRecord::Base self.abstract_class = true connects_to shards: { default: { writing: :primary }, shard_one: { writing: :primary_shard_one } }Swap between shards in your controller / model code:
ActiveRecord::Base.connected_to(shard: :shard_one) do # Read from shard one endThe horizontal sharding API also supports read replicas. See guides for more details.
Eileen M. Uchitelle, John Crepezzi
-
Deprecate
spec_namein favor ofnameon database configurations.The accessors for
spec_nameonconfigs_forandDatabaseConfigare deprecated. Please usenameinstead.Deprecated behavior:
db_config = ActiveRecord::Base.configs_for(env_name: "development", spec_name: "primary") db_config.spec_nameNew behavior:
db_config = ActiveRecord::Base.configs_for(env_name: "development", name: "primary") db_config.nameEileen M. Uchitelle
-
Add additional database-specific rake tasks for multi-database users.
Previously,
rails db:create,rails db:drop, andrails db:migratewere the only rails tasks that could operate on a single database. For example:rails db:create rails db:create:primary rails db:create:animals rails db:drop rails db:drop:primary rails db:drop:animals rails db:migrate rails db:migrate:primary rails db:migrate:animalsWith these changes,
rails db:schema:dump,rails db:schema:load,rails db:structure:dump,rails db:structure:loadandrails db:test:preparecan additionally operate on a single database. For example:rails db:schema:dump rails db:schema:dump:primary rails db:schema:dump:animals rails db:schema:load rails db:schema:load:primary rails db:schema:load:animals rails db:structure:dump rails db:structure:dump:primary rails db:structure:dump:animals rails db:structure:load rails db:structure:load:primary rails db:structure:load:animals rails db:test:prepare rails db:test:prepare:primary rails db:test:prepare:animalsKyle Thompson
-
Add support for
strict_loadingmode on association declarations.Raise an error if attempting to load a record from an association that has been marked as
strict_loadingunless it was explicitly eager loaded.Usage:
class Developer < ApplicationRecord has_many :projects, strict_loading: true end dev = Developer.first dev.projects.first # => ActiveRecord::StrictLoadingViolationError: The projects association is marked as strict_loading and cannot be lazily loaded.Kevin Deisz
-
Add support for
strict_loadingmode to prevent lazy loading of records.Raise an error if a parent record is marked as
strict_loadingand attempts to lazily load its associations. This is useful for finding places you may want to preload an association and avoid additional queries.Usage:
dev = Developer.strict_loading.first dev.audit_logs.to_a # => ActiveRecord::StrictLoadingViolationError: Developer is marked as strict_loading and AuditLog cannot be lazily loaded.Eileen M. Uchitelle, Aaron Patterson
-
Add support for PostgreSQL 11+ partitioned indexes when using
upsert_all.Sebastián Palma
-
Adds support for
if_not_existstoadd_columnandif_existstoremove_column.Applications can set their migrations to ignore exceptions raised when adding a column that already exists or when removing a column that does not exist.
Example Usage:
class AddColumnTitle < ActiveRecord::Migration[6.1] def change add_column :posts, :title, :string, if_not_exists: true end endclass RemoveColumnTitle < ActiveRecord::Migration[6.1] def change remove_column :posts, :title, if_exists: true end endEileen M. Uchitelle
-
Regexp-escape table name for MS SQL Server.
Add
Regexp.escapeto one method in ActiveRecord, so that table names with regular expression characters in them work as expected. Since MS SQL Server uses "[" and "]" to quote table and column names, and those characters are regular expression characters, methods likepluckandselectfail in certain cases when used with the MS SQL Server adapter.Larry Reid
-
Store advisory locks on their own named connection.
Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped.
In order to fix this we are storing the advisory lock on a new connection with the connection specification name
AdvisoryLockBase. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this.Eileen M. Uchitelle, John Crepezzi
-
Allow schema cache path to be defined in the database configuration file.
For example:
development: adapter: postgresql database: blog_development pool: 5 schema_cache_path: tmp/schema/main.ymlKatrina Owen
-
Deprecate
#remove_connectionin favor of#remove_connection_poolwhen called on the handler.#remove_connectionis deprecated in order to support returning aDatabaseConfigobject instead of aHash. Use#remove_connection_pool,#remove_connectionwill be removed in 6.2.Eileen M. Uchitelle, John Crepezzi
-
Deprecate
#default_hashand it's alias#[]on database configurations.Applications should use
configs_for.#default_hashand#[]will be removed in 6.2.Eileen M. Uchitelle, John Crepezzi
-
Add scale support to
ActiveRecord::Validations::NumericalityValidator.Gannon McGibbon
-
Find orphans by looking for missing relations through chaining
where.missing:Before:
Post.left_joins(:author).where(authors: { id: nil })After:
Post.where.missing(:author)Tom Rossi
-
Ensure
:readingconnections always raise if a write is attempted.Now Rails will raise an
ActiveRecord::ReadOnlyErrorif any connection on the reading handler attempts to make a write. If your reading role needs to write you should name the role something other than:reading.Eileen M. Uchitelle
-
Deprecate
"primary"as theconnection_specification_nameforActiveRecord::Base."primary"has been deprecated as theconnection_specification_nameforActiveRecord::Basein favor of using"ActiveRecord::Base". This change affects calls toActiveRecord::Base.connection_handler.retrieve_connectionandActiveRecord::Base.connection_handler.remove_connection. If you're calling these methods with"primary", please switch to"ActiveRecord::Base".Eileen M. Uchitelle, John Crepezzi
-
Add
ActiveRecord::Validations::NumericalityValidatorwith support for casting floats using a database columns' precision value.Gannon McGibbon
-
Enforce fresh ETag header after a collection's contents change by adding ActiveRecord::Relation#cache_key_with_version. This method will be used by ActionController::ConditionalGet to ensure that when collection cache versioning is enabled, requests using ConditionalGet don't return the same ETag header after a collection is modified.
Fixes #38078.
Aaron Lipman
-
Skip test database when running
db:createordb:dropin development withDATABASE_URLset.Brian Buchalter
-
Don't allow mutations on the database configurations hash.
Freeze the configurations hash to disallow directly changing it. If applications need to change the hash, for example to create databases for parallelization, they should use the
DatabaseConfigobject directly.Before:
@db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary") @db_config.configuration_hash.merge!(idle_timeout: "0.02")After:
@db_config = ActiveRecord::Base.configurations.configs_for(env_name: "test", spec_name: "primary") config = @db_config.configuration_hash.merge(idle_timeout: "0.02") db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(@db_config.env_name, @db_config.spec_name, config)Eileen M. Uchitelle, John Crepezzi
-
Remove
:connection_idfrom thesql.active_recordnotification.Aaron Patterson, Rafael Mendonça França
-
The
:namekey will no longer be returned as part ofDatabaseConfig#configuration_hash. Please useDatabaseConfig#owner_nameinstead.Eileen M. Uchitelle, John Crepezzi
-
ActiveRecord's
belongs_to_required_by_defaultflag can now be set per model.You can now opt-out/opt-in specific models from having their associations required by default.
This change is meant to ease the process of migrating all your models to have their association required.
Edouard Chin
-
The
connection_configmethod has been deprecated, please useconnection_db_configinstead which will return aDatabaseConfigurations::DatabaseConfiginstead of aHash.Eileen M. Uchitelle, John Crepezzi
-
Retain explicit selections on the base model after applying
includesandjoins.Resolves #34889.
Patrick Rebsch
-
The
databasekwarg is deprecated without replacement because it can't be used for sharding and creates an issue if it's used during a request. Applications that need to create new connections should useconnects_toinstead.Eileen M. Uchitelle, John Crepezzi
-
Allow attributes to be fetched from Arel node groupings.
Jeff Emminger, Gannon McGibbon
-
A database URL can now contain a querystring value that contains an equal sign. This is needed to support passing PostgreSQL
options.Joshua Flanagan
-
Calling methods like
establish_connectionwith aHashwhich is invalid (eg: noadapter) will now raise an error the same way as connections defined inconfig/database.yml.John Crepezzi
-
Specifying
implicit_order_columnnow subsorts the records by primary key if available to ensure deterministic results.Paweł Urbanek
-
where(attr => [])now loads an empty result without making a query.John Hawthorn
-
Fixed the performance regression for
primary_keysintroduced MySQL 8.0.Hiroyuki Ishii
-
Add support for
belongs_totohas_manyinversing.Gannon McGibbon
-
Allow length configuration for
has_secure_tokenmethod. The minimum length is set at 24 characters.Before:
has_secure_token :auth_tokenAfter:
has_secure_token :default_token # 24 characters has_secure_token :auth_token, length: 36 # 36 characters has_secure_token :invalid_token, length: 12 # => ActiveRecord::SecureToken::MinimumLengthErrorBernardo de Araujo
-
Deprecate
DatabaseConfigurations#to_h. These connection hashes are still available viaActiveRecord::Base.configurations.configs_for.Eileen Uchitelle, John Crepezzi
-
Add
DatabaseConfig#configuration_hashto return database configuration hashes with symbol keys, and use all symbol-key configuration hashes internally. DeprecateDatabaseConfig#configwhich returns a String-keyedHashwith the same values.John Crepezzi, Eileen Uchitelle
-
Allow column names to be passed to
remove_indexpositionally along with other options.Passing other options can be necessary to make
remove_indexcorrectly reversible.Before:
add_index :reports, :report_id # => works add_index :reports, :report_id, unique: true # => works remove_index :reports, :report_id # => works remove_index :reports, :report_id, unique: true # => ArgumentErrorAfter:
remove_index :reports, :report_id, unique: true # => worksEugene Kenny
-
Allow bulk
ALTERstatements to drop and recreate indexes with the same name.Eugene Kenny
-
insert,insert_all,upsert, andupsert_allnow clear the query cache.Eugene Kenny
-
Call
while_preventing_writesdirectly fromconnected_to.In some cases application authors want to use the database switching middleware and make explicit calls with
connected_to. It's possible for an app to turn off writes and not turn them back on by the time we callconnected_to(role: :writing).This change allows apps to fix this by assuming if a role is writing we want to allow writes, except in the case it's explicitly turned off.
Eileen M. Uchitelle
-
Improve detection of ActiveRecord::StatementTimeout with mysql2 adapter in the edge case when the query is terminated during filesort.
Kir Shatrov
-
Stop trying to read yaml file fixtures when loading Active Record fixtures.
Gannon McGibbon
-
Deprecate
.reorder(nil)with.first/.first!taking non-deterministic result.To continue taking non-deterministic result, use
.take/.take!instead.Ryuta Kamizono
-
Preserve user supplied joins order as much as possible.
Fixes #36761, #34328, #24281, #12953.
Ryuta Kamizono
-
Allow
matches_regexanddoes_not_match_regexpon the MySQL Arel visitor.James Pearson
-
Allow specifying fixtures to be ignored by setting
ignorein YAML file's '_fixture' section.Tongfei Gao
-
Make the DATABASE_URL env variable only affect the primary connection. Add new env variables for multiple databases.
John Crepezzi, Eileen Uchitelle
-
Add a warning for enum elements with 'not_' prefix.
class Foo enum status: [:sent, :not_sent] endEdu Depetris
-
Make currency symbols optional for money column type in PostgreSQL.
Joel Schneider
-
Add support for beginless ranges, introduced in Ruby 2.7.
Josh Goodall
-
Add
database_exists?method to connection adapters to check if a database exists.Guilherme Mansur
-
Loading the schema for a model that has no
table_nameraises aTableNotSpecifiederror.Guilherme Mansur, Eugene Kenny
-
PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.
Fixes #36022.
Ryuta Kamizono
-
Make ActiveRecord
ConnectionPool.connectionsmethod thread-safe.Fixes #36465.
Jeff Doering
-
Add support for multiple databases to
rails db:abort_if_pending_migrations.Mark Lee
-
Fix sqlite3 collation parsing when using decimal columns.
Martin R. Schuster
-
Fix invalid schema when primary key column has a comment.
Fixes #29966.
Guilherme Goettems Schneider
-
Fix table comment also being applied to the primary key column.
Guilherme Goettems Schneider
-
Allow generated
create_tablemigrations to include or skip timestamps.Michael Duchemin
Action View
-
SanitizeHelper.sanitized_allowed_attributes and SanitizeHelper.sanitized_allowed_tags call safe_list_sanitizer's class method
Fixes #39586
Taufiq Muhammadi
-
Change form_with to generate non-remote forms by default.
form_withwould generate a remote form by default. This would confuse users because they were forced to handle remote requests.All new 6.1 applications will generate non-remote forms by default. When upgrading a 6.0 application you can enable remote forms by default by setting
config.action_view.form_with_generates_remote_formstotrue.Petrik de Heus
-
Yield translated strings to calls of
ActionView::FormBuilder#buttonwhen a block is given.Sean Doyle
-
Alias
ActionView::Helpers::Tags::Label::LabelBuilder#translationto#to_sso thatform.labelcalls can yield that value to their blocks.Sean Doyle
-
Rename the new
TagHelper#class_namesmethod toTagHelper#token_list, and make the original available as an alias.token_list("foo", "foo bar") # => "foo bar"Sean Doyle
-
ARIA Array and Hash attributes are treated as space separated
DOMTokenListvalues. This is useful when declaring lists of label text identifiers inaria-labelledbyoraria-describedby.tag.input type: 'checkbox', name: 'published', aria: { invalid: @post.errors[:published].any?, labelledby: ['published_context', 'published_label'], describedby: { published_errors: @post.errors[:published].any? } } #=> <input type="checkbox" name="published" aria-invalid="true" aria-labelledby="published_context published_label" aria-describedby="published_errors" >Sean Doyle
-
Remove deprecated
escape_whitelistfromActionView::Template::Handlers::ERB.Rafael Mendonça França
-
Remove deprecated
find_all_anywherefromActionView::Resolver.Rafael Mendonça França
-
Remove deprecated
formatsfromActionView::Template::HTML.Rafael Mendonça França
-
Remove deprecated
formatsfromActionView::Template::RawFile.Rafael Mendonça França
-
Remove deprecated
formatsfromActionView::Template::Text.Rafael Mendonça França
-
Remove deprecated
find_filefromActionView::PathSet.Rafael Mendonça França
-
Remove deprecated
rendered_formatfromActionView::LookupContext.Rafael Mendonça França
-
Remove deprecated
find_filefromActionView::ViewPaths.Rafael Mendonça França
-
Require that
ActionView::Basesubclasses implement#compiled_method_container.Rafael Mendonça França
-
Remove deprecated support to pass an object that is not a
ActionView::LookupContextas the first argument inActionView::Base#initialize.Rafael Mendonça França
-
Remove deprecated
formatargumentActionView::Base#initialize.Rafael Mendonça França
-
Remove deprecated
ActionView::Template#refresh.Rafael Mendonça França
-
Remove deprecated
ActionView::Template#original_encoding.Rafael Mendonça França
-
Remove deprecated
ActionView::Template#variants.Rafael Mendonça França
-
Remove deprecated
ActionView::Template#formats.Rafael Mendonça França
-
Remove deprecated
ActionView::Template#virtual_path=.Rafael Mendonça França
-
Remove deprecated
ActionView::Template#updated_at.Rafael Mendonça França
-
Remove deprecated
updated_atargument required onActionView::Template#initialize.Rafael Mendonça França
-
Make
localsargument required onActionView::Template#initialize.Rafael Mendonça França
-
Remove deprecated
ActionView::Template.finalize_compiled_template_methods.Rafael Mendonça França
-
Remove deprecated
config.action_view.finalize_compiled_template_methodsRafael Mendonça França
-
Remove deprecated support to calling
ActionView::ViewPaths#with_fallbackwith a block.Rafael Mendonça França
-
Remove deprecated support to passing absolute paths to
render template:.Rafael Mendonça França
-
Remove deprecated support to passing relative paths to
render file:.Rafael Mendonça França
-
Remove support to template handlers that don't accept two arguments.
Rafael Mendonça França
-
Remove deprecated pattern argument in
ActionView::Template::PathResolver.Rafael Mendonça França
-
Remove deprecated support to call private methods from object in some view helpers.
Rafael Mendonça França
-
ActionView::Helpers::TranslationHelper#translateaccepts a block, yielding the translated text and the fully resolved translation key:<%= translate(".relative_key") do |translation, resolved_key| %> <span title="<%= resolved_key %>"><%= translation %></span> <% end %>Sean Doyle
-
Ensure cache fragment digests include all relevant template dependencies when fragments are contained in a block passed to the render helper. Remove the virtual_path keyword arguments found in CacheHelper as they no longer possess any function following 1581cab.
Fixes #38984.
Aaron Lipman
-
Deprecate
config.action_view.raise_on_missing_translationsin favor ofconfig.i18n.raise_on_missing_translations.New generalized configuration option now determines whether an error should be raised for missing translations in controllers and views.
fatkodima
-
Instrument layout rendering in
TemplateRenderer#render_with_layoutasrender_layout.action_view, and include (when necessary) the layout's virtual path in notification payloads for collection and partial renders.Zach Kemp
-
ActionView::Base.annotate_rendered_view_with_filenamesannotates HTML output with template file names.Joel Hawksley, Aaron Patterson
-
ActionView::Helpers::TranslationHelper#translatereturns nil when passeddefault: nilwithout a translation matchingI18n#translate.Stefan Wrobel
-
OptimizedFileSystemResolverprefers template details in order of locale, formats, variants, handlers.Iago Pimenta
-
Added
class_nameshelper to create a CSS class value with conditional classes.Joel Hawksley, Aaron Patterson
-
Add support for conditional values to TagBuilder.
Joel Hawksley
-
ActionView::Helpers::FormOptionsHelper#selectshould mark option fornilas selected.@post = Post.new @post.category = nil # Before select("post", "category", none: nil, programming: 1, economics: 2) # => # <select name="post[category]" id="post_category"> # <option value="">none</option> # <option value="1">programming</option> # <option value="2">economics</option> # </select> # After select("post", "category", none: nil, programming: 1, economics: 2) # => # <select name="post[category]" id="post_category"> # <option selected="selected" value="">none</option> # <option value="1">programming</option> # <option value="2">economics</option> # </select>bogdanvlviv
-
Log lines for partial renders and started template renders are now emitted at the
DEBUGlevel instead ofINFO.Completed template renders are still logged at the
INFOlevel.DHH
-
ActionView::Helpers::SanitizeHelper: support rails-html-sanitizer 1.1.0.
Juanito Fatas
-
Added
phone_tohelper method to create a link from mobile numbers.Pietro Moro
-
annotated_source_code returns an empty array so TemplateErrors without a template in the backtrace are surfaced properly by DebugExceptions.
Guilherme Mansur, Kasper Timm Hansen
-
Add autoload for SyntaxErrorInTemplate so syntax errors are correctly raised by DebugExceptions.
Guilherme Mansur, Gannon McGibbon
-
RenderingHelpersupports rendering objects thatrespond_to?:render_in.Joel Hawksley, Natasha Umer, Aaron Patterson, Shawn Allen, Emily Plummer, Diana Mounter, John Hawthorn, Nathan Herald, Zaid Zawaideh, Zach Ahn
-
Fix
select_tagso that it doesn't changeoptionswheninclude_blankis present.Younes SERRAJ
Action Pack
-
Support for the HTTP header
Feature-Policyhas been revised to reflect its rename toPermissions-Policy.Rails.application.config.permissions_policy do |p| p.camera :none p.gyroscope :none p.microphone :none p.usb :none p.fullscreen :self p.payment :self, "https://secure-example.com" endJulien Grillot
-
Allow
ActionDispatch::HostAuthorizationto exclude specific requests.Host Authorization checks can be skipped for specific requests. This allows for health check requests to be permitted for requests with missing or non-matching host headers.
Chris Bisnett
-
Add
config.action_dispatch.request_id_headerto allow changing the name of the unique X-Request-Id headerArlston Fernandes
-
Deprecate
config.action_dispatch.return_only_media_type_on_content_type.Rafael Mendonça França
-
Change
ActionDispatch::Response#content_typeto return the full Content-Type header.Rafael Mendonça França
-
Remove deprecated
ActionDispatch::Http::ParameterFilter.Rafael Mendonça França
-
Added support for exclusive no-store Cache-Control header.
If
no-storeis set on Cache-Control header it is exclusive (all other cache directives are dropped).Chris Kruger
-
Catch invalid UTF-8 parameters for POST requests and respond with BadRequest.
Additionally, perform
#set_binary_encodinginActionDispatch::Http::Request#GETandActionDispatch::Http::Request#POSTprior to validating encoding.Adrianna Chang
-
Allow
assert_recognizesrouting assertions to work on mounted root routes.Gannon McGibbon
-
Change default redirection status code for non-GET/HEAD requests to 308 Permanent Redirect for
ActionDispatch::SSL.Alan Tan, Oz Ben-David
-
Fix
follow_redirect!to follow redirection with same HTTP verb when following a 308 redirection.Alan Tan
-
When multiple domains are specified for a cookie, a domain will now be chosen only if it is equal to or is a superdomain of the request host.
Jonathan Hefner
-
ActionDispatch::Statichandles precompiled Brotli (.br) files.Adds to existing support for precompiled gzip (.gz) files. Brotli files are preferred due to much better compression.
When the browser requests /some.js with
Accept-Encoding: br, we check for public/some.js.br and serve that file, if present, withContent-Encoding: brandVary: Accept-Encodingheaders.Ryan Edward Hall, Jeremy Daer
-
Add raise_on_missing_translations support for controllers.
This configuration determines whether an error should be raised for missing translations. It can be enabled through
config.i18n.raise_on_missing_translations. Note that described configuration also affects raising error for missing translations in views.fatkodima
-
Added
compactandcompact!toActionController::Parameters.Eugene Kenny
-
Calling
each_pairoreach_valueon anActionController::Parameterswithout passing a block now returns an enumerator.Eugene Kenny
-
fixture_file_uploadnow uses path relative tofile_fixture_pathPreviously the path had to be relative to
fixture_path. You can change your existing code as follow:# Before fixture_file_upload('files/dog.png') # After fixture_file_upload('dog.png')Edouard Chin
-
Remove deprecated
force_sslat the controller level.Rafael Mendonça França
-
The +helper+ class method for controllers loads helper modules specified as strings/symbols with
String#constantizeinstead ofrequire_dependency.Remember that support for strings/symbols is only a convenient API. You can always pass a module object:
helper UtilsHelperwhich is recommended because it is simple and direct. When a string/symbol is received,
helperjust manipulates and inflects the argument to obtain that same module object.Xavier Noria, Jean Boussier
-
Correctly identify the entire localhost IPv4 range as trusted proxy.
Nick Soracco
-
url_forwill now use "https://" as the default protocol whenRails.application.config.force_sslis set to true.Jonathan Hefner
-
Accept and default to base64_urlsafe CSRF tokens.
Base64 strict-encoded CSRF tokens are not inherently websafe, which makes them difficult to deal with. For example, the common practice of sending the CSRF token to a browser in a client-readable cookie does not work properly out of the box: the value has to be url-encoded and decoded to survive transport.
Now, we generate Base64 urlsafe-encoded CSRF tokens, which are inherently safe to transport. Validation accepts both urlsafe tokens, and strict-encoded tokens for backwards compatibility.
Scott Blum
-
Support rolling deploys for cookie serialization/encryption changes.
In a distributed configuration like rolling update, users may observe both old and new instances during deployment. Users may be served by a new instance and then by an old instance.
That means when the server changes
cookies_serializerfrom:marshalto:hybridor the server changesuse_authenticated_cookie_encryptionfromfalsetotrue, users may lose their sessions if they access the server during deployment.We added fallbacks to downgrade the cookie format when necessary during deployment, ensuring compatibility on both old and new instances.
Masaki Hara
-
ActionDispatch::Request.remote_iphas ip address even when all sites are trusted.Before, if all
X-Forwarded-Forsites were trusted, theremote_ipwould default to127.0.0.1. Now, the furthest proxy site is used. e.g.: It now gives an ip address when using curl from the load balancer.Keenan Brock
-
Fix possible information leak / session hijacking vulnerability.
The
ActionDispatch::Session::MemcacheStoreis still vulnerable given it requires the gem dalli to be updated as well.CVE-2019-16782.
-
Include child session assertion count in ActionDispatch::IntegrationTest.
IntegrationTest#open_sessionusesdupto create the new session, which meant it had its own copy of@assertions. This prevented the assertions from being correctly counted and reported.Child sessions now have their
attr_accessoroverridden to delegate to the root session.Fixes #32142.
Sam Bostock
-
Add SameSite protection to every written cookie.
Enabling
SameSitecookie protection is an addition to CSRF protection, where cookies won't be sent by browsers in cross-site POST requests when set to:lax.:strictdisables cookies being sent in cross-site GET or POST requests.Passing
:nonedisables this protection and is the same as previous versions albeit a; SameSite=Noneis appended to the cookie.See upgrade instructions in config/initializers/new_framework_defaults_6_1.rb.
More info here
NB: Technically already possible as Rack supports SameSite protection, this is to ensure it's applied to all cookies
Cédric Fabianski
-
Bring back the feature that allows loading external route files from the router.
This feature existed back in 2012 but got reverted with the incentive that https://github.com/rails/routing_concerns was a better approach. Turned out that this wasn't fully the case and loading external route files from the router can be helpful for applications with a really large set of routes. Without this feature, application needs to implement routes reloading themselves and it's not straightforward.
# config/routes.rb Rails.application.routes.draw do draw(:admin) end # config/routes/admin.rb get :foo, to: 'foo#bar'Yehuda Katz, Edouard Chin
-
Fix system test driver option initialization for non-headless browsers.
glaszig
-
redirect_to.action_controllernotifications now include theActionDispatch::Requestin their payloads as:request.Austin Story
-
respond_to#anyno longer returns a response's Content-Type based on the request format but based on the block given.Example:
def my_action respond_to do |format| format.any { render(json: { foo: 'bar' }) } end end get('my_action.csv')The previous behaviour was to respond with a
text/csvContent-Type which is inaccurate since a JSON response is being rendered.Now it correctly returns a
application/jsonContent-Type.Edouard Chin
-
Replaces (back)slashes in failure screenshot image paths with dashes.
If a failed test case contained a slash or a backslash, a screenshot would be created in a nested directory, causing issues with
tmp:clear.Damir Zekic
-
Add
params.member?to mimic Hash behavior.Younes Serraj
-
process_action.action_controllernotifications now include the following in their payloads::request- theActionDispatch::Request:response- theActionDispatch::Response
George Claghorn
-
Updated
ActionDispatch::Request.remote_ipsetter to clear set the instanceremote_iptonilbefore setting the header that the value is derived from.Fixes #37383.
Norm Provost
-
ActionController::Base.log_atallows setting a different log level per request.# Use the debug level if a particular cookie is set. class ApplicationController < ActionController::Base log_at :debug, if: -> { cookies[:debug] } endGeorge Claghorn
-
Allow system test screen shots to be taken more than once in a test by prefixing the file name with an incrementing counter.
Add an environment variable
RAILS_SYSTEM_TESTING_SCREENSHOT_HTMLto enable saving of HTML during a screenshot in addition to the image. This uses the same image name, with the extension replaced with.htmlTom Fakes
-
Add
Vary: Acceptheader when usingAcceptheader for response.For some requests like
/users/1, Rails uses requests'Acceptheader to determine what to return. And if we don't addVaryin the response header, browsers might accidentally cache different types of content, which would cause issues: e.g. javascript got displayed instead of html content. This PR fixes these issues by addingVary: Acceptin these types of requests. For more detailed problem description, please read:https://github.com/rails/rails/pull/36213
Fixes #25842.
Stan Lo
-
Fix IntegrationTest
follow_redirect!to follow redirection using the same HTTP verb when following a 307 redirection.Edouard Chin
-
System tests require Capybara 3.26 or newer.
George Claghorn
-
Reduced log noise handling ActionController::RoutingErrors.
Alberto Fernández-Capel
-
Add DSL for configuring HTTP Feature Policy.
This new DSL provides a way to configure an HTTP Feature Policy at a global or per-controller level. Full details of HTTP Feature Policy specification and guidelines can be found at MDN:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy
Example global policy:
Rails.application.config.feature_policy do |f| f.camera :none f.gyroscope :none f.microphone :none f.usb :none f.fullscreen :self f.payment :self, "https://secure.example.com" endExample controller level policy:
class PagesController < ApplicationController feature_policy do |p| p.geolocation "https://example.com" end endJacob Bednarz
-
Add the ability to set the CSP nonce only to the specified directives.
Fixes #35137.
Yuji Yaginuma
-
Keep part when scope option has value.
When a route was defined within an optional scope, if that route didn't take parameters the scope was lost when using path helpers. This commit ensures scope is kept both when the route takes parameters or when it doesn't.
Fixes #33219.
Alberto Almagro
-
Added
deep_transform_keysanddeep_transform_keys!methods to ActionController::Parameters.Gustavo Gutierrez
-
Calling
ActionController::Parameters#transform_keys/!without a block now returns an enumerator for the parameters instead of the underlying hash.Eugene Kenny
-
Fix strong parameters blocks all attributes even when only some keys are invalid (non-numerical). It should only block invalid key's values instead.
Stan Lo
Active Job
-
Recover nano precision when serializing
Time,TimeWithZoneandDateTimeobjects.Alan Tan
-
Deprecate
config.active_job.return_false_on_aborted_enqueue.Rafael Mendonça França
-
Return
falsewhen enqueuing a job is aborted.Rafael Mendonça França
-
While using
perform_enqueued_jobstest helper enqueued jobs must be stored for the later check withassert_enqueued_with.Dmitry Polushkin
-
ActiveJob::TestCase#perform_enqueued_jobswithout a block removes performed jobs from the queue.That way the helper can be called multiple times and not perform a job invocation multiple times.
def test_jobs HelloJob.perform_later("rafael") perform_enqueued_jobs # only runs with "rafael" HelloJob.perform_later("david") perform_enqueued_jobs # only runs with "david" endÉtienne Barrié
-
ActiveJob::TestCase#perform_enqueued_jobswill no longer perform retries:When calling
perform_enqueued_jobswithout a block, the adapter will now perform jobs that are already in the queue. Jobs that will end up in the queue afterwards won't be performed.This change only affects
perform_enqueued_jobswhen no block is given.Edouard Chin
-
Add queue name support to Que adapter.
Brad Nauta, Wojciech Wnętrzak
-
Don't run
after_enqueueandafter_performcallbacks if the callback chain is halted.class MyJob < ApplicationJob before_enqueue { throw(:abort) } after_enqueue { # won't enter here anymore } endafter_enqueueandafter_performcallbacks will no longer run if the callback chain is halted. This behaviour is a breaking change and won't take effect until Rails 6.2. To enable this behaviour in your app right now, you can add in your app's configuration fileconfig.active_job.skip_after_callbacks_if_terminated = true.Edouard Chin
-
Fix enqueuing and performing incorrect logging message.
Jobs will no longer always log "Enqueued MyJob" or "Performed MyJob" when they actually didn't get enqueued/performed.
class MyJob < ApplicationJob before_enqueue { throw(:abort) } end MyJob.perform_later # Will no longer log "Enqueued MyJob" since job wasn't even enqueued through adapter.A new message will be logged in case a job couldn't be enqueued, either because the callback chain was halted or because an exception happened during enqueuing. (i.e. Redis is down when you try to enqueue your job)
Edouard Chin
-
Add an option to disable logging of the job arguments when enqueuing and executing the job.
class SensitiveJob < ApplicationJob self.log_arguments = false def perform(my_sensitive_argument) end endWhen dealing with sensitive arguments as password and tokens it is now possible to configure the job to not put the sensitive argument in the logs.
Rafael Mendonça França
-
Changes in
queue_name_prefixof a job no longer affects all other jobs.Fixes #37084.
Lucas Mansur
-
Allow
ClassandModuleinstances to be serialized.Kevin Deisz
-
Log potential matches in
assert_enqueued_withandassert_performed_with.Gareth du Plooy
-
Add
atargument to theperform_enqueued_jobstest helper.John Crepezzi, Eileen Uchitelle
-
assert_enqueued_withandassert_performed_withcan now test jobs with relative delay.Vlado Cingel
-
Add jitter to
ActiveJob::Exceptions.retry_on.ActiveJob::Exceptions.retry_onnow uses a random amount of jitter in order to prevent the thundering herd effect. Defaults to 15% (represented as 0.15) but overridable via the:jitteroption when usingretry_on. Jitter is applied when anInteger,ActiveSupport::Durationor:exponentially_longer, is passed to thewaitargument inretry_on.retry_on(MyError, wait: :exponentially_longer, jitter: 0.30)Anthony Ross
Action Mailer
-
Change default queue name of the deliver (
:mailers) job to be the job adapter's default (:default).Rafael Mendonça França
-
Remove deprecated
ActionMailer::Base.receivein favor of Action Mailbox.Rafael Mendonça França
-
Fix ActionMailer assertions don't work for parameterized mail with legacy delivery job.
bogdanvlviv
-
Added
email_address_with_nameto properly escape addresses with names.Sunny Ripert
Action Cable
-
ActionCable::Connection::Basenow allows intercepting unhandled exceptions withrescue_frombefore they are logged, which is useful for error reporting tools and other integrations.Justin Talbott
-
Add
ActionCable::Channel#stream_or_reject_forto stream if record is present, otherwise reject the connectionAtul Bhosale
-
Add
ActionCable::Channel#stop_stream_fromand#stop_stream_forto unsubscribe from a specific stream.Zhang Kang
-
Add PostgreSQL subscription connection identificator.
Now you can distinguish Action Cable PostgreSQL subscription connections among others. Also, you can set custom
idincable.ymlconfiguration.SELECT application_name FROM pg_stat_activity; /* application_name ------------------------ psql ActionCable-PID-42 (2 rows) */Sergey Ponomarev
-
Subscription confirmations and rejections are now logged at the
DEBUGlevel instead ofINFO.DHH
Active Storage
-
Change default queue name of the analysis (
:active_storage_analysis) and purge (:active_storage_purge) jobs to be the job adapter's default (:default).Rafael Mendonça França
-
Implement
strict_loadingon ActiveStorage associations.David Angulo
-
Remove deprecated support to pass
:combine_optionsoperations toActiveStorage::Transformers::ImageProcessing.Rafael Mendonça França
-
Remove deprecated
ActiveStorage::Transformers::MiniMagickTransformer.Rafael Mendonça França
-
Remove deprecated
config.active_storage.queue.Rafael Mendonça França
-
Remove deprecated
ActiveStorage::Downloading.Rafael Mendonça França
-
Add per-environment configuration support
Pietro Moro
-
The Poppler PDF previewer renders a preview image using the original document's crop box rather than its media box, hiding print margins. This matches the behavior of the MuPDF previewer.
Vincent Robert
-
Touch parent model when an attachment is purged.
Víctor Pérez Rodríguez
-
Files can now be served by proxying them from the underlying storage service instead of redirecting to a signed service URL. Use the
rails_storage_proxy_pathand_urlhelpers to proxy an attached file:<%= image_tag rails_storage_proxy_path(@user.avatar) %>To proxy by default, set
config.active_storage.resolve_model_to_route:# Proxy attached files instead. config.active_storage.resolve_model_to_route = :rails_storage_proxy<%= image_tag @user.avatar %>To redirect to a signed service URL when the default file serving strategy is set to proxying, use the
rails_storage_redirect_pathand_urlhelpers:<%= image_tag rails_storage_redirect_path(@user.avatar) %>Jonathan Fleckenstein
-
Add
config.active_storage.web_image_content_typesto allow applications to add content types (likeimage/webp) in which variants can be processed, instead of letting those images be converted to the fallback PNG format.Jeroen van Haperen
-
Add support for creating variants of
WebPimages out of the box.Dino Maric
-
Only enqueue analysis jobs for blobs with non-null analyzer classes.
Gannon McGibbon
-
Previews are created on the same service as the original blob.
Peter Zhu
-
Remove unused
dispositionandcontent_typequery parameters forDiskService.Peter Zhu
-
Use
DiskControllerfor both public and private files.DiskControlleris able to handle multiple services by adding aservice_namefield in the generated URL inDiskService.Peter Zhu
-
Variants are tracked in the database to avoid existence checks in the storage service.
George Claghorn
-
Deprecate
service_urlmethods in favour ofurl.Deprecate
Variant#service_urlandPreview#service_urlto instead use#urlmethod to be consistent withBlob.Peter Zhu
-
Permanent URLs for public storage blobs.
Services can be configured in
config/storage.ymlwith a new keypublic: true | falseto indicate whether a service holds public blobs or private blobs. Public services will always return a permanent URL.Deprecates
Blob#service_urlin favor ofBlob#url.Peter Zhu
-
Make services aware of configuration names.
Gannon McGibbon
-
The
Content-Typeheader is set on image variants when they're uploaded to third-party storage services.Kyle Ribordy
-
Allow storage services to be configured per attachment.
class User < ActiveRecord::Base has_one_attached :avatar, service: :s3 end class Gallery < ActiveRecord::Base has_many_attached :photos, service: :s3 endDmitry Tsepelev
-
You can optionally provide a custom blob key when attaching a new file:
user.avatar.attach key: "avatars/#{user.id}.jpg", io: io, content_type: "image/jpeg", filename: "avatar.jpg"Active Storage will store the blob's data on the configured service at the provided key.
George Claghorn
-
Replace
Blob.create_after_upload!withBlob.create_and_upload!and deprecate the former.create_after_upload!has been removed since it could lead to data corruption by uploading to a key on the storage service which happened to be already taken. Creating the record would then correctly raise a database uniqueness exception but the stored object would already have overwritten another.create_and_upload!swaps the order of operations so that the key gets reserved up-front or the uniqueness error gets raised, before the upload to a key takes place.Julik Tarkhanov
-
Set content disposition in direct upload using
filenameanddispositionparameters toActiveStorage::Service#headers_for_direct_upload.Peter Zhu
-
Allow record to be optionally passed to blob finders to make sharding easier.
Gannon McGibbon
-
Switch from
azure-storagegem toazure-storage-blobgem for Azure service.Peter Zhu
-
Add
config.active_storage.draw_routesto disable Active Storage routes.Gannon McGibbon
-
Image analysis is skipped if ImageMagick returns an error.
ActiveStorage::Analyzer::ImageAnalyzer#metadatawould previously raise aMiniMagick::Error, which caused persistentActiveStorage::AnalyzeJobfailures. It now logs the error and returns{}, resulting in no metadata being added to the offending image blob.George Claghorn
-
Method calls on singular attachments return
nilwhen no file is attached.Previously, assuming the following User model,
user.avatar.filenamewould raise aModule::DelegationErrorif no avatar was attached:class User < ApplicationRecord has_one_attached :avatar endThey now return
nil.Matthew Tanous
-
The mirror service supports direct uploads.
New files are directly uploaded to the primary service. When a directly-uploaded file is attached to a record, a background job is enqueued to copy it to each secondary service.
Configure the queue used to process mirroring jobs by setting
config.active_storage.queues.mirror. The default is:active_storage_mirror.George Claghorn
-
The S3 service now permits uploading files larger than 5 gigabytes.
When uploading a file greater than 100 megabytes in size, the service transparently switches to multipart uploads using a part size computed from the file's total size and S3's part count limit.
No application changes are necessary to take advantage of this feature. You can customize the default 100 MB multipart upload threshold in your S3 service's configuration:
production: service: s3 access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> region: us-east-1 bucket: my-bucket upload: multipart_threshold: <%= 250.megabytes %>George Claghorn
Action Mailbox
-
Change default queue name of the incineration (
:action_mailbox_incineration) and routing (:action_mailbox_routing) jobs to be the job adapter's default (:default).Rafael Mendonça França
-
Sendgrid ingress now passes through the envelope recipient as
X-Original-To.Mark Haussmann
-
Update Mandrill inbound email route to respond appropriately to HEAD requests for URL health checks from Mandrill.
Bill Cromie
-
Add way to deliver emails via source instead of filling out a form through the conductor interface.
DHH
-
Mailgun ingress now passes through the envelope recipient as
X-Original-To.Rikki Pitt
-
Deprecate
Rails.application.credentials.action_mailbox.api_keyandMAILGUN_INGRESS_API_KEYin favor ofRails.application.credentials.action_mailbox.signing_keyandMAILGUN_INGRESS_SIGNING_KEY.Matthijs Vos
-
Allow easier creation of multi-part emails from the
create_inbound_email_from_mailandreceive_inbound_email_from_mailtest helpers.Michael Herold
-
Fix Bcc header not being included with emails from
create_inbound_email_fromtest helpers.jduff
-
Add
ApplicationMailbox.mailbox_forto expose mailbox routing.James Dabbs
Action Text
-
Declare
ActionText::FixtureSet.attachmentto generate an<action-text-attachment sgid="..."></action-text-attachment>element with a validsgidattribute.hello_world_review_content: record: hello_world (Review) name: content body: <p><%= ActionText::FixtureSet.attachment("messages", :hello_world) %> is great!</p>Sean Doyle
-
Locate
fill_in_rich_text_areaby<label>textIn addition to searching for
<trix-editor>elements with the appropriatearia-labelattribute, also support locating elements that match the corresponding<label>element's text.Sean Doyle
-
Be able to add a default value to
rich_text_area.form.rich_text_area :content, value: "<h1>Hello world</h1>" #=> <input type="hidden" name="message[content]" id="message_content_trix_input_message_1" value="<h1>Hello world</h1>">Paulo Ancheta
-
Add method to confirm rich text content existence by adding
?after rich text attribute.message = Message.create!(body: "<h1>Funny times!</h1>") message.body? #=> trueKyohei Toyoda
-
The
fill_in_rich_text_areasystem test helper locates a Trix editor and fills it in with the given HTML.# <trix-editor id="message_content" ...></trix-editor> fill_in_rich_text_area "message_content", with: "Hello <em>world!</em>" # <trix-editor placeholder="Your message here" ...></trix-editor> fill_in_rich_text_area "Your message here", with: "Hello <em>world!</em>" # <trix-editor aria-label="Message content" ...></trix-editor> fill_in_rich_text_area "Message content", with: "Hello <em>world!</em>" # <input id="trix_input_1" name="message[content]" type="hidden"> # <trix-editor input="trix_input_1"></trix-editor> fill_in_rich_text_area "message[content]", with: "Hello <em>world!</em>"George Claghorn
Railties
-
Added
Railtie#serverhook called when Rails starts a server. This is useful in case your application or a library needs to run another process next to the Rails server. This is quite common in development for instance to run the Webpack or the React server.It can be used like this:
class MyRailtie < Rails::Railtie server do WebpackServer.run end endEdouard Chin
-
Remove deprecated
rake dev:cachetasks.Rafael Mendonça França
-
Remove deprecated
rake routestasks.Rafael Mendonça França
-
Remove deprecated
rake initializerstasks.Rafael Mendonça França
-
Remove deprecated support for using the
HOSTenvironment variable to specify the server IP.Rafael Mendonça França
-
Remove deprecated
serverargument from the rails server command.Rafael Mendonça França
-
Remove deprecated
SOURCE_ANNOTATION_DIRECTORIESenvironment variable support fromrails notes.Rafael Mendonça França
-
Remove deprecated
connectionoption in therails dbconsolecommand.Rafael Mendonça França
-
Remove depreated
rake notestasks.Rafael Mendonça França
-
Return a 405 Method Not Allowed response when a request uses an unknown HTTP method.
Fixes #38998.
Loren Norman
-
Make railsrc file location xdg-specification compliant
rails newwill now look for the defaultrailsrcfile at$XDG_CONFIG_HOME/rails/railsrc(or~/.config/rails/railsrcifXDG_CONFIG_HOMEis not set). If this file does not exist,rails newwill fall back to~/.railsrc.The fallback behaviour means this does not cause any breaking changes.
Nick Wolf
-
Change the default logging level from :debug to :info to avoid inadvertent exposure of personally identifiable information (PII) in production environments.
Eric M. Payne
-
Automatically generate abstract class when using multiple databases.
When generating a scaffold for a multiple database application, Rails will now automatically generate the abstract class for the database when the database argument is passed. This abstract class will include the connection information for the writing configuration and any models generated for that database will automatically inherit from the abstract class.
Usage:
$ bin/rails generate scaffold Pet name:string --database=animalsWill create an abstract class for the animals connection.
class AnimalsRecord < ApplicationRecord self.abstract_class = true connects_to database: { writing: :animals } endAnd generate a
Petmodel that inherits from the newAnimalsRecord:class Pet < AnimalsRecord endIf you already have an abstract class and it follows a different pattern than Rails defaults, you can pass a parent class with the database argument.
$ bin/rails generate scaffold Pet name:string --database=animals --parent=SecondaryBaseThis will ensure the model inherits from the
SecondaryBaseparent instead ofAnimalsRecordclass Pet < SecondaryBase endEileen M. Uchitelle, John Crepezzi
-
Accept params from url to prepopulate the Inbound Emails form in Rails conductor.
Chris Oliver
-
Create a new rails app using a minimal stack.
rails new cool_app --minimalAll the following are excluded from your minimal stack:
- action_cable
- action_mailbox
- action_mailer
- action_text
- active_job
- active_storage
- bootsnap
- jbuilder
- spring
- system_tests
- turbolinks
- webpack
Haroon Ahmed, DHH
-
Add default ENV variable option with BACKTRACE to turn off backtrace cleaning when debugging framework code in the generated config/initializers/backtrace_silencers.rb.
BACKTRACE=1 ./bin/rails runner "MyClass.perform"DHH
-
The autoloading guide for Zeitwerk mode documents how to autoload classes during application boot in a safe way.
Haroon Ahmed, Xavier Noria
-
The
classicautoloader starts its deprecation cycle.New Rails projects are strongly discouraged from using
classic, and we recommend that existing projects running onclassicswitch tozeitwerkmode when upgrading. Please check the Upgrading Ruby on Rails guide for tips.Xavier Noria
-
Adds
rails test:allfor running all tests in the test directory.This runs all test files in the test directory, including system tests.
Niklas Häusele
-
Add
config.generators.after_generatefor processing to generated files.Register a callback that will get called right after generators has finished.
Yuji Yaginuma
-
Make test file patterns configurable via Environment variables
This makes test file patterns configurable via two environment variables:
DEFAULT_TEST, to configure files to test, andDEFAULT_TEST_EXCLUDE, to configure files to exclude from testing.These values were hardcoded before, which made it difficult to add new categories of tests that should not be executed by default (e.g: smoke tests).
Jorge Manrubia
-
No longer include
rake rdoctask when generating plugins.To generate docs, use the
rdoc libcommand instead.Jonathan Hefner
-
Allow relative paths with trailing slashes to be passed to
rails test.Eugene Kenny
-
Add
rack-mini-profilergem to the defaultGemfile.rack-mini-profilerdisplays performance information such as SQL time and flame graphs. It's enabled by default in development environment, but can be enabled in production as well. See the gem README for information on how to enable it in production.Osama Sayegh
-
rails statswill now count TypeScript files toward JavaScript stats.Joshua Cody
-
Run
git initwhen generating plugins.Opt out with
--skip-git.OKURA Masafumi
-
Add benchmark generator.
Introduce benchmark generator to benchmark Rails applications.
rails generate benchmark opt_compareThis creates a benchmark file that uses
benchmark-ips. By default, two code blocks can be benchmarked using thebeforeandafterreports.You can run the generated benchmark file using:
ruby script/benchmarks/opt_compare.rbKevin Jalbert, Gannon McGibbon
-
Cache compiled view templates when running tests by default.
When generating a new app without
--skip-spring, caching classes is disabled inenvironments/test.rb. This implicitly disables caching view templates too. This change will enable view template caching by adding this to the generatedenvironments/test.rb:config.action_view.cache_template_loading = trueJorge Manrubia
-
Introduce middleware move operations.
With this change, you no longer need to delete and reinsert a middleware to move it from one place to another in the stack:
config.middleware.move_before ActionDispatch::Flash, Magical::UnicornsThis will move the
Magical::Unicornsmiddleware beforeActionDispatch::Flash. You can also move it after with:config.middleware.move_after ActionDispatch::Flash, Magical::UnicornsGenadi Samokovarov
-
Generators that inherit from NamedBase respect
--forceoption.Josh Brody
-
Allow configuration of eager_load behaviour for rake environment:
config.rake_eager_loadDefaults to
falseas per previous behaviour.Thierry Joyal
-
Ensure Rails migration generator respects system-wide primary key config.
When rails is configured to use a specific primary key type:
config.generators do |g| g.orm :active_record, primary_key_type: :uuid endPreviously:
$ bin/rails g migration add_location_to_users location:referencesThe references line in the migration would not have
type: :uuid. This change causes the type to be applied appropriately.Louis-Michel Couture, Dermot Haughey
-
Deprecate
Rails::DBConsole#config.Rails::DBConsole#configis deprecated without replacement. UseRails::DBConsole.db_config.configuration_hashinstead.Eileen M. Uchitelle, John Crepezzi
-
Rails.application.config_formerges shared configuration deeply.# config/example.yml shared: foo: bar: baz: 1 development: foo: bar: qux: 2# Previously Rails.application.config_for(:example)[:foo][:bar] #=> { qux: 2 } # Now Rails.application.config_for(:example)[:foo][:bar] #=> { baz: 1, qux: 2 }Yuhei Kiriyama
-
Remove access to values in nested hashes returned by
Rails.application.config_forvia String keys.# config/example.yml development: options: key: valueRails.application.config_for(:example).optionsThis used to return a Hash on which you could access values with String keys. This was deprecated in 6.0, and now doesn't work anymore.
Étienne Barrié
-
Configuration files for environments (
config/environments/*.rb) are now able to modifyautoload_paths,autoload_once_paths, andeager_load_paths.As a consequence, applications cannot autoload within those files. Before, they technically could, but changes in autoloaded classes or modules had no effect anyway in the configuration because reloading does not reboot.
Ways to use application code in these files:
-
Define early in the boot process a class that is not reloadable, from which the application takes configuration values that get passed to the framework.
# In config/application.rb, for example. require "#{Rails.root}/lib/my_app/config" # In config/environments/development.rb, for example. config.foo = MyApp::Config.foo -
If the class has to be reloadable, then wrap the configuration code in a
to_prepareblock:config.to_prepare do config.foo = MyModel.foo endThat assigns the latest
MyModel.footoconfig.foowhen the application boots, and each time there is a reload. But whether that has an effect or not depends on the configuration point, since it is not uncommon for engines to read the application configuration during initialization and set their own state from them. That process happens only on boot, not on reloads, and if that is howconfig.fooworked, resetting it would have no effect in the state of the engine.
Allen Hsu & Xavier Noria
-
-
Support using environment variable to set pidfile.
Ben Thorner
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Symbol is allowed by default for YAML columns
Étienne Barrié
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
Active Support
-
Fix tag helper regression.
Eileen Uchitelle
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
Action Text
-
Disentangle Action Text from ApplicationController
Allow Action Text to be used without having an ApplicationController defined. This makes sure:
- Action Text attachments render the correct URL host in mailers.
- an ActionController::Renderer isn't allocated per request.
- Sidekiq doesn't hang with the "classic" autoloader.
Jonathan Hefner
Active Support
-
Fixed issue in
ActiveSupport::Cache::RedisCacheStorenot passing options toread_multicausingfetch_multito not work properly.Rajesh Sharma
-
with_optionscopies its options hash again to avoid leaking mutations.Fixes #39343.
Eugene Kenny
Active Model
- No changes.
Active Record
-
Only warn about negative enums if a positive form that would cause conflicts exists.
Fixes #39065.
Alex Ghiculescu
-
Allow the inverse of a
has_oneassociation that was previously autosaved to be loaded.Fixes #34255.
Steven Weber
-
Reset statement cache for association if
table_nameis changed.Fixes #36453.
Ryuta Kamizono
-
Type cast extra select for eager loading.
Ryuta Kamizono
-
Prevent collection associations from being autosaved multiple times.
Fixes #39173.
Eugene Kenny
-
Resolve issue with insert_all unique_by option when used with expression index.
When the
:unique_byoption ofActiveRecord::Persistence.insert_allandActiveRecord::Persistence.upsert_allwas used with the name of an expression index, an error was raised. Adding a guard around the formatting behavior for the:unique_bycorrects this.Usage:
create_table :books, id: :integer, force: true do |t| t.column :name, :string t.index "lower(name)", unique: true end Book.insert_all [{ name: "MyTest" }], unique_by: :index_books_on_lower_nameFixes #39516.
Austen Madden
-
Fix preloading for polymorphic association with custom scope.
Ryuta Kamizono
-
Allow relations with different SQL comments in the
ormethod.Takumi Shotoku
-
Resolve conflict between counter cache and optimistic locking.
Bump an Active Record instance's lock version after updating its counter cache. This avoids raising an unnecessary
ActiveRecord::StaleObjectErrorupon subsequent transactions by maintaining parity with the corresponding database record'slock_versioncolumn.Fixes #16449.
Aaron Lipman
-
Fix through association with source/through scope which has joins.
Ryuta Kamizono
-
Fix through association to respect source scope for includes/preload.
Ryuta Kamizono
-
Fix eager load with Arel joins to maintain the original joins order.
Ryuta Kamizono
-
Fix group by count with eager loading + order + limit/offset.
Ryuta Kamizono
-
Fix left joins order when merging multiple left joins from different associations.
Ryuta Kamizono
-
Fix index creation to preserve index comment in bulk change table on MySQL.
Ryuta Kamizono
-
Change
remove_foreign_keyto not check:validateoption if database doesn't support the feature.Ryuta Kamizono
-
Fix the result of aggregations to maintain duplicated "group by" fields.
Ryuta Kamizono
-
Do not return duplicated records when using preload.
Bogdan Gusiev
Action View
-
SanitizeHelper.sanitized_allowed_attributes and SanitizeHelper.sanitized_allowed_tags call safe_list_sanitizer's class method
Fixes #39586
Taufiq Muhammadi
Action Pack
-
Accept base64_urlsafe CSRF tokens to make forward compatible.
Base64 strict-encoded CSRF tokens are not inherently websafe, which makes them difficult to deal with. For example, the common practice of sending the CSRF token to a browser in a client-readable cookie does not work properly out of the box: the value has to be url-encoded and decoded to survive transport.
In Rails 6.1, we generate Base64 urlsafe-encoded CSRF tokens, which are inherently safe to transport. Validation accepts both urlsafe tokens, and strict-encoded tokens for backwards compatibility.
In Rails 5.2.5, the CSRF token format is accidentally changed to urlsafe-encoded. If you upgrade apps from 5.2.5, set the config
urlsafe_csrf_tokens = true.Rails.application.config.action_controller.urlsafe_csrf_tokens = trueScott Blum, Étienne Barrié
-
Signed and encrypted cookies can now store
falseas their value whenaction_dispatch.use_cookies_with_metadatais enabled.Rolandas Barysas
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
The Poppler PDF previewer renders a preview image using the original document's crop box rather than its media box, hiding print margins. This matches the behavior of the MuPDF previewer.
Vincent Robert
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Allow relative paths with trailing slashes to be passed to
rails test.Eugene Kenny
-
Return a 405 Method Not Allowed response when a request uses an unknown HTTP method.
Fixes #38998.
Loren Norman
In this version, we fixed warnings when used with Ruby 2.7 across the entire framework.
Following are the list of other changes, per-framework.
Active Support
-
Array#to_sentenceno longer returns a frozen string.Before:
['one', 'two'].to_sentence.frozen? # => trueAfter:
['one', 'two'].to_sentence.frozen? # => falseNicolas Dular
-
Update
ActiveSupport::Messages::Metadata#fresh?to work for cookies with expiry set whenActiveSupport.parse_json_times = true.Christian Gregg
Active Model
- No changes.
Active Record
-
Recommend applications don't use the
databasekwarg inconnected_toThe database kwarg in
connected_towas meant to be used for one-off scripts but is often used in requests. This is really dangerous because it re-establishes a connection every time. It's deprecated in 6.1 and will be removed in 6.2 without replacement. This change soft deprecates it in 6.0 by removing documentation.Eileen M. Uchitelle
-
Fix support for PostgreSQL 11+ partitioned indexes.
Sebastián Palma
-
Add support for beginless ranges, introduced in Ruby 2.7.
Josh Goodall
-
Fix insert_all with enum values
Fixes #38716.
Joel Blum
-
Regexp-escape table name for MS SQL
Add
Regexp.escapeto one method in ActiveRecord, so that table names with regular expression characters in them work as expected. Since MS SQL Server uses "[" and "]" to quote table and column names, and those characters are regular expression characters, methods likepluckandselectfail in certain cases when used with the MS SQL Server adapter.Larry Reid
-
Store advisory locks on their own named connection.
Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped.
In order to fix this we are storing the advisory lock on a new connection with the connection specification name
AdisoryLockBase. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this.Eileen M. Uchitelle, John Crepezzi
-
Ensure
:readingconnections always raise if a write is attempted.Now Rails will raise an
ActiveRecord::ReadOnlyErrorif any connection on the reading handler attempts to make a write. If your reading role needs to write you should name the role something other than:reading.Eileen M. Uchitelle
-
Enforce fresh ETag header after a collection's contents change by adding ActiveRecord::Relation#cache_key_with_version. This method will be used by ActionController::ConditionalGet to ensure that when collection cache versioning is enabled, requests using ConditionalGet don't return the same ETag header after a collection is modified. Fixes #38078.
Aaron Lipman
-
A database URL can now contain a querystring value that contains an equal sign. This is needed to support passing PostgresSQL
options.Joshua Flanagan
-
Retain explicit selections on the base model after applying
includesandjoins.Resolves #34889.
Patrick Rebsch
Action View
-
annotated_source_code returns an empty array so TemplateErrors without a template in the backtrace are surfaced properly by DebugExceptions.
Guilherme Mansur, Kasper Timm Hansen
-
Add autoload for SyntaxErrorInTemplate so syntax errors are correctly raised by DebugExceptions.
Guilherme Mansur, Gannon McGibbon
Action Pack
-
Include child session assertion count in ActionDispatch::IntegrationTest
IntegrationTest#open_sessionusesdupto create the new session, which meant it had its own copy of@assertions. This prevented the assertions from being correctly counted and reported.Child sessions now have their
attr_accessoroverriden to delegate to the root session.Fixes #32142
Sam Bostock
Active Job
-
While using
perform_enqueued_jobstest helper enqueued jobs must be stored for the later check withassert_enqueued_with.Dmitry Polushkin
-
Add queue name support to Que adapter
Brad Nauta, Wojciech Wnętrzak
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
-
Update Mandrill inbound email route to respond appropriately to HEAD requests for URL health checks from Mandrill.
Bill Cromie
Action Text
- No changes.
Railties
-
Cache compiled view templates when running tests by default
When generating a new app without
--skip-spring, caching classes is disabled inenvironments/test.rb. This implicitly disables caching view templates too. This change will enable view template caching by adding this to the generatedenvironments/test.rb:config.action_view.cache_template_loading = trueJorge Manrubia
-
Rails::Application#eager_load!is available again to load application code manually as it was possible in previous versions.Please, note this is not integrated with the whole eager loading logic that runs when Rails boots with eager loading enabled, you can think of this method as a vanilla recursive code loader.
This ability has been restored because there are some use cases for it, such as indexers that need to have all application classes and modules in memory.
Xavier Noria
-
Generators that inherit from NamedBase respect
--forceoptionJosh Brody
-
Regression fix: The Rake task
zeitwerk:checksupports eager loaded namespaces which do not have eager load paths, like the recently addedi18n. These namespaces are only required to respond toeager_load!.Xavier Noria
Active Support
-
Eager load translations during initialization.
Diego Plentz
-
Use per-thread CPU time clock on
ActiveSupport::Notifications.George Claghorn
Active Model
- No changes.
Active Record
-
Share the same connection pool for primary and replica databases in the transactional tests for the same database.
Edouard Chin
-
Fix the preloader when one record is fetched using
after_initializebut not the entire collection.Bradley Price
-
Fix collection callbacks not terminating when
:abortis thrown.Edouard Chin, Ryuta Kamizono
-
Correctly deprecate
where.notworking as NOR for relations.12a9664 deprecated where.not working as NOR, however doing a relation query like
where.not(relation: { ... })wouldn't be properly deprecated andwhere.notwould work as NAND instead.Edouard Chin
-
Fix
db:migratetask with multiple databases to restore the connection to the previous database.The migrate task iterates and establish a connection over each db resulting in the last one to be used by subsequent rake tasks. We should reestablish a connection to the connection that was established before the migrate tasks was run
Edouard Chin
-
Fix multi-threaded issue for
AcceptanceValidator.Ryuta Kamizono
Action View
- No changes.
Action Pack
-
Allow using mountable engine route helpers in System Tests.
Chalo Fernandez
Active Job
-
Allow Sidekiq access to the underlying job class.
By having access to the Active Job class, Sidekiq can get access to any
sidekiq_optionswhich have been set on that Active Job type and serialize those options into Redis.https://github.com/mperham/sidekiq/blob/master/Changes.md#60
Mike Perham
Action Mailer
-
Fix ActionMailer assertions don't work for parameterized mail with legacy delivery job.
bogdanvlviv
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Fix the collision check for the scaffold generator.
Ryan Robeson
Active Support
-
ActiveSupport::SafeBuffersupportsEnumeratormethods.Shugo Maeda
-
The Redis cache store fails gracefully when the server returns a "max number of clients reached" error.
Brandon Medenwald
-
Fixed that mutating a value returned by a memory cache store would unexpectedly change the cached value.
Jonathan Hyman
-
The default inflectors in
zeitwerkmode support overrides:# config/initializers/zeitwerk.rb Rails.autoloaders.each do |autoloader| autoloader.inflector.inflect( "html_parser" => "HTMLParser", "ssl_error" => "SSLError" ) endThat way, you can tweak how individual basenames are inflected without touching Active Support inflection rules, which are global. These inflectors fallback to
String#camelize, so existing inflection rules are still taken into account for non-overridden basenames.Please, check the autoloading guide for
zeitwerkmode if you prefer not to depend onString#camelizeat all.Xavier Noria
-
Improve
Range#===,Range#include?, andRange#cover?to work with beginless (startless) and endless range targets.Allen Hsu, Andrew Hodgkinson
-
Don't use
Process#clock_gettime(CLOCK_PROCESS_CPUTIME_ID)on SolarisIain Beeston
Active Model
- No changes.
Active Record
-
Common Table Expressions are allowed on read-only connections.
Chris Morris
-
New record instantiation respects
unscope.Ryuta Kamizono
-
Fixed a case where
find_in_batchescould halt too early.Takayuki Nakata
-
Autosaved associations always perform validations when a custom validation context is used.
Tekin Suleyman
-
sql.active_recordnotifications now include the:connectionin their payloads.Eugene Kenny
-
A rollback encountered in an
after_commitcallback does not reset previously-committed record state.Ryuta Kamizono
-
Fixed that join order was lost when eager-loading.
Ryuta Kamizono
-
DESCRIBEqueries are allowed on read-only connections.Dylan Thacker-Smith
-
Fixed that records that had been
inspected could not be marshaled.Eugene Kenny
-
The connection pool reaper thread is respawned in forked processes. This fixes that idle connections in forked processes wouldn't be reaped.
John Hawthorn
-
The memoized result of
ActiveRecord::Relation#takeis properly cleared whenActiveRecord::Relation#resetorActiveRecord::Relation#reloadis called.Anmol Arora
-
Fixed the performance regression for
primary_keysintroduced MySQL 8.0.Hiroyuki Ishii
-
insert,insert_all,upsert, andupsert_allnow clear the query cache.Eugene Kenny
-
Call
while_preventing_writesdirectly fromconnected_to.In some cases application authors want to use the database switching middleware and make explicit calls with
connected_to. It's possible for an app to turn off writes and not turn them back on by the time we callconnected_to(role: :writing).This change allows apps to fix this by assuming if a role is writing we want to allow writes, except in the case it's explicitly turned off.
Eileen M. Uchitelle
-
Improve detection of ActiveRecord::StatementTimeout with mysql2 adapter in the edge case when the query is terminated during filesort.
Kir Shatrov
Action View
-
UJS avoids
Element.closest()for IE 9 compatibility.George Claghorn
Action Pack
-
ActionDispatch::SystemTestCasenow inherits fromActiveSupport::TestCaserather thanActionDispatch::IntegrationTest. This permits running jobs in system tests.George Claghorn, Edouard Chin
-
Registered MIME types may contain extra flags:
Mime::Type.register "text/html; fragment", :html_fragmentAaron Patterson
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
ActiveStorage::AnalyzeJobs are discarded onActiveRecord::RecordNotFounderrors.George Claghorn
-
Blobs are recorded in the database before being uploaded to the service. This fixes that generated blob keys could silently collide, leading to data loss.
Julik Tarkhanov
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
The
zeitwerk:checkRake task reports files outside the app's root directory, as in engines loaded from gems.Xavier Noria
-
Fixed a possible error when using the evented file update checker.
Yuji Yaginuma
-
The sqlite3 database files created by the parallel testing feature are included in the default
.gitignorefile for newly-generated apps.Yasuo Honda
-
rails newgenerates a.keepfile intmp/pids. This fixes starting a server viarackupinstead ofrails server.Rafael Mendonça França
Active Support
-
Fix tag helper regression.
Eileen Uchitelle
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
Active Support
-
Restore support to Ruby 2.2.
ojab
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Fix
ActiveStorage.supported_image_processing_methodsandActiveStorage.unsupported_image_processing_argumentsthat were not being applied.Rafael Mendonça França
Railties
- No changes.
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Accept base64_urlsafe CSRF tokens to make forward compatible.
Base64 strict-encoded CSRF tokens are not inherently websafe, which makes them difficult to deal with. For example, the common practice of sending the CSRF token to a browser in a client-readable cookie does not work properly out of the box: the value has to be url-encoded and decoded to survive transport.
In this version, we generate Base64 urlsafe-encoded CSRF tokens, which are inherently safe to transport. Validation accepts both urlsafe tokens, and strict-encoded tokens for backwards compatibility.
How the tokes are encoded is controllr by the
action_controller.urlsafe_csrf_tokensconfig.In Rails 5.2.5, the CSRF token format was accidentally changed to urlsafe-encoded.
Atention: If you already upgraded your application to 5.2.5, set the config
urlsafe_csrf_tokenstotrue, otherwise your form submission will start to fail during the deploy of this new version.Rails.application.config.action_controller.urlsafe_csrf_tokens = trueIf you are upgrading from 5.2.4.x, you don't need to change this configuration.
Scott Blum, Étienne Barrié
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Marcel is upgraded to version 1.0.0 to avoid a dependency on GPL-licensed mime types data.
George Claghorn
Railties
- No changes.
Active Support
-
Make ActiveSupport::Logger Fiber-safe. Fixes #36752.
Use
Fiber.current.__id__inActiveSupport::Logger#local_level=in order to make log level local to Ruby Fibers in addition to Threads.Example:
logger = ActiveSupport::Logger.new(STDOUT) logger.level = 1 p "Main is debug? #{logger.debug?}" Fiber.new { logger.local_level = 0 p "Thread is debug? #{logger.debug?}" }.resume p "Main is debug? #{logger.debug?}"Before:
Main is debug? false Thread is debug? true Main is debug? trueAfter:
Main is debug? false Thread is debug? true Main is debug? falseAlexander Varnin
Active Model
-
Type cast falsy boolean symbols on boolean attribute as false.
Fixes #35676.
Ryuta Kamizono
Active Record
-
Fix circular
autosave: truecauses invalid records to be saved.Prior to the fix, when there was a circular series of
autosave: trueassociations, the callback for ahas_manyassociation was run while another instance of the same callback on the same association hadn't finished running. When control returned to the first instance of the callback, the instance variable had changed, and subsequent associated records weren't saved correctly. Specifically, the ID field for thebelongs_tocorresponding to thehas_manywasnil.Fixes #28080.
Larry Reid
-
PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.
Fixes #36022.
Ryuta Kamizono
-
Fix sqlite3 collation parsing when using decimal columns.
Martin R. Schuster
-
Make ActiveRecord
ConnectionPool.connectionsmethod thread-safe.Fixes #36465.
Jeff Doering
-
Assign all attributes before calling
buildto ensure the child record is visible inbefore_addandafter_addcallbacks forhas_many :throughassociations.Fixes #33249.
Ryan H. Kerr
Action View
-
Allow programmatic click events to trigger Rails UJS click handlers. Programmatic click events (eg. ones generated by
Rails.fire(link, "click")) don't specify a button. These events were being incorrectly stopped by code meant to ignore scroll wheel and right clicks introduced in #34573.Sudara Williams
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
-
Use original
bundlerenvironment variables during the process of generating a new rails project.Marco Costa
-
Allow loading seeds without ActiveJob.
Fixes #35782
Jeremy Weathers
-
Only force
:asyncActiveJob adapter to:inlineduring seeding.BatedUrGonnaDie
Active Support
-
Add
ActiveSupport::HashWithIndifferentAccess#assoc.assoccan now be called with either a string or a symbol.Stefan Schüßler
-
Fix
String#safe_constantizethrowing aLoadErrorfor incorrectly cased constant references.Keenan Brock
-
Allow Range#=== and Range#cover? on Range
Range#cover?can now accept a range argument likeRange#include?andRange#===.Range#===works correctly on Ruby 2.6.Range#include?is moved into a new file, with these two methods.utilum
-
If the same block is
includedmultiple times for a Concern, an exception is no longer raised.Mark J. Titorenko, Vlad Bokov
Active Model
-
Fix date value when casting a multiparameter date hash to not convert from Gregorian date to Julian date.
Before:
Day.new({"day(1i)"=>"1", "day(2i)"=>"1", "day(3i)"=>"1"}) => #<Day id: nil, day: "0001-01-03", created_at: nil, updated_at: nil>After:
Day.new({"day(1i)"=>"1", "day(2i)"=>"1", "day(3i)"=>"1"}) => #<Day id: nil, day: "0001-01-01", created_at: nil, updated_at: nil>Fixes #28521.
Sayan Chakraborty
-
Fix numericality equality validation of
BigDecimalandFloatby casting toBigDecimalon both ends of the validation.Gannon McGibbon
Active Record
-
Fix different
countcalculation when usingsizewith manualselectwith DISTINCT.Fixes #35214.
Juani Villarejo
-
Fix prepared statements caching to be enabled even when query caching is enabled.
Ryuta Kamizono
-
Don't allow
wherewith invalid value matches to nil values.Fixes #33624.
Ryuta Kamizono
-
Restore an ability that class level
updatewithout giving ids.Fixes #34743.
Ryuta Kamizono
-
Fix join table column quoting with SQLite.
Gannon McGibbon
-
Ensure that
delete_allon collection proxy returns affected count.Ryuta Kamizono
-
Reset scope after delete on collection association to clear stale offsets of removed records.
Gannon McGibbon
Action View
-
Prevent non-primary mouse keys from triggering Rails UJS click handlers. Firefox fires click events even if the click was triggered by non-primary mouse keys such as right- or scroll-wheel-clicks. For example, right-clicking a link such as the one described below (with an underlying ajax request registered on click) should not cause that request to occur.
<%= link_to 'Remote', remote_path, class: 'remote', remote: true, data: { type: :json } %>Fixes #34541
Wolfgang Hobmaier
Action Pack
-
Allow using combine the Cache Control
publicandno-cacheheaders.Before this change, even if
publicwas specified for Cache Control header, it was excluded whenno-cachewas included. This fixed to keeppublicheader as is.Fixes #34780.
Yuji Yaginuma
-
Allow
nilparams forActionController::TestCase.Ryo Nakamura
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
-
Seed database with inline ActiveJob job adapter.
Gannon McGibbon
-
Fix boolean interaction in scaffold system tests.
Gannon McGibbon
Active Support
-
Fix bug where
#to_optionsforActiveSupport::HashWithIndifferentAccesswould not act as alias for#symbolize_keys.Nick Weiland
-
Improve the logic that detects non-autoloaded constants.
Jan Habermann, Xavier Noria
-
Fix bug where
URI.unescapewould 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::CompatibilityErrorAshe Connor, Aaron Patterson
Active Model
-
Fix numericality validator to still use value before type cast except Active Record.
Fixes #33651, #33686.
Ryuta Kamizono
Active Record
-
Do not ignore the scoping with query methods in the scope block.
Ryuta Kamizono
-
Allow aliased attributes to be used in
#update_columnsand#update.Gannon McGibbon
-
Allow spaces in postgres table names.
Fixes issue where "user post" is misinterpreted as ""user"."post"" when quoting table names with the postgres adapter.
Gannon McGibbon
-
Cached columns_hash fields should be excluded from ResultSet#column_types
PR #34528 addresses the inconsistent behaviour when attribute is defined for an ignored column. The following test was passing for SQLite and MySQL, but failed for PostgreSQL:
class DeveloperName < ActiveRecord::Type::String def deserialize(value) "Developer: #{value}" end end class AttributedDeveloper < ActiveRecord::Base self.table_name = "developers" attribute :name, DeveloperName.new self.ignored_columns += ["name"] end developer = AttributedDeveloper.create developer.update_column :name, "name" loaded_developer = AttributedDeveloper.where(id: developer.id).select("*").first puts loaded_developer.name # should be "Developer: name" but it's just "name"Dmitry Tsepelev
-
Values of enum are frozen, raising an error when attempting to modify them.
Emmanuel Byrd
-
update_columnsnow correctly raisesActiveModel::MissingAttributeErrorif the attribute does not exist.Sean Griffin
-
Do not use prepared statement in queries that have a large number of binds.
Ryuta Kamizono
-
Fix query cache to load before first request.
Eileen M. Uchitelle
-
Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error.
Fixes #33056.
Federico Martinez
-
Fix duplicated record creation when using nested attributes with
create_with.Darwin Wu
-
Fix regression setting children record in parent
before_savecallback.Guo Xiang Tan
-
Prevent leaking of user's DB credentials on
rails db:createfailure.bogdanvlviv
-
Clear mutation tracker before continuing the around callbacks.
Yuya Tanaka
-
Prevent deadlocks when waiting for connection from pool.
Brent Wheeldon
-
Avoid extra scoping when using
Relation#updatethat was causing this method to change the current scope.Ryuta Kamizono
-
Fix numericality validator not to be affected by custom getter.
Ryuta Kamizono
-
Fix bulk change table ignores comment option on PostgreSQL.
Yoshiyuki Kinjo
Action View
- No changes.
Action Pack
-
Reset Capybara sessions if failed system test screenshot raising an exception.
Reset Capybara sessions if
take_failed_screenshotraise exception in system testafter_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 selfand now it generates:
Content-Security-Policy: default-src 'self'Andrew White
-
Fix
rails routes -cfor controller name consists of multiple word.Yoshiyuki Kinjo
-
Call the
#redirect_toblock in controller context.Steven Peckins
Active Job
-
Make sure
assert_enqueued_with()&assert_performed_with()work reliably with hash arguments.Sharang Dashputre
-
Restore
ActionController::Parameterssupport toActiveJob::Arguments.serialize.Bernie Chiu
-
Restore
HashWithIndifferentAccesssupport toActiveJob::Arguments.deserialize.Gannon McGibbon
-
Include deserialized arguments in job instances returned from
assert_enqueued_withandassert_performed_withAlan Wu
-
Increment execution count before deserialize arguments.
Currently, the execution count increments after deserializes arguments. Therefore, if an error occurs with deserialize, it retries indefinitely.
Yuji Yaginuma
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Support multiple submit buttons in Active Storage forms.
Chrıs Seelus
-
Fix
ArgumentErrorwhen uploading to amazon s3Hiroki Sanpei
-
Add a foreign-key constraint to the
active_storage_attachmentstable for blobs.George Claghorn
-
Discard
ActiveStorage::PurgeJobsfor missing blobs.George Claghorn
-
Fix uploading Tempfiles to Azure Storage.
George Claghorn
Railties
-
Disable content security policy for mailer previews.
Dylan Reile
-
Log the remote IP address of clients behind a proxy.
Atul Bhosale
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Fix
touchoption to behave consistently withPersistence#touchmethod.Ryuta Kamizono
-
Back port Rails 5.2
reverse_orderArel SQL literal fix.Matt Jones, Brooke Kuhlmann
-
becomesshould clear the mutation tracker which is created inafter_initialize.Fixes #32867.
Ryuta Kamizono
Action View
-
Fix issue with
button_to'sto_form_paramsbutton_towas throwing exception when invoked withparamshash that contains symbol and string keys. The reason for the exception was thatto_form_paramswas comparing the given symbol and string keys.The issue is fixed by turning all keys to strings inside
to_form_paramsbefore comparing them.Georgi Georgiev
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Railties
- No changes.