Recent Releases of https://github.com/rails/rails
https://github.com/rails/rails - 7.0.2.2
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix Reloader method signature to work with the new Executor signature
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 7.0.2.1
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Under certain circumstances, the middleware isn't informed that the
response body has been fully closed which result in request state not
being fully reset before the next request[CVE-2022-23633]
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.1.4.6
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix Reloader method signature to work with the new Executor signature
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.1.4.5
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Under certain circumstances, the middleware isn't informed that the
response body has been fully closed which result in request state not
being fully reset before the next request[CVE-2022-23633]
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.0.4.6
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix Reloader method signature to work with the new Executor signature
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.0.4.5
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Under certain circumstances, the middleware isn't informed that the
response body has been fully closed which result in request state not
being fully reset before the next request[CVE-2022-23633]
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 5.2.6.2
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix Reloader method signature to work with the new Executor signature
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 5.2.6.1
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Under certain circumstances, the middleware isn't informed that the
response body has been fully closed which result in request state not
being fully reset before the next request[CVE-2022-23633]
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 7.0.2
Active Support
-
Fix
ActiveSupport::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_proxy
fixes 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 now
when 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.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 7.0.1
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_needed
was 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_now
is called.Example:
class UpdateUserJob < ActiveJob::Base discard_on ActiveJob::DeserializationError def perform(user) # ... end end # In the test User.destroy_all assert_nothing_raised do perform_enqueued_jobs only: UpdateUserJob 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
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 7.0.0
Action Cable
-
The Action Cable client now ensures successful channel subscriptions:
- The client maintains a set of pending subscriptions until either
the server confirms the subscription or the channel is torn down. - Rectifies the race condition where an unsubscribe is rapidly followed
by a subscribe (on the same channel identifier) and the requests are
handled out of order by the ActionCable server, thereby ignoring the
subscribe command.
Daniel Spinosa
- The client maintains a set of pending subscriptions until either
-
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
- The client will wait a random amount between 1x and 3x of the stale
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::DeliveryJob
in 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
aNo 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 the
config.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::ParseError
to 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 inrescued_responses.It may be too noisy to get all backtraces logged for applications that manage uncaught
exceptions viarescued_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_proxies
asRemoteIpmiddleware 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_tagand
rich_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
extensiblelayouts/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.erb
partial.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 to
ActionView::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 the
FormBuilder#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 the
ActionView::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
Profile
model 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 transformformmethod
attributes into_method="$VERB"Form Data to enable varied same-form actions:<%= form_with model: post, method: :put do %> <%= form.button "Update" %> <%= form.button "Delete", formmethod: :delete %> <% end %> <%# => <form action="posts/1"> => <input type="hidden" name="_method" value="put"> => <button type="submit">Update</button> => <button type="submit" formmethod="post" name="_method" value="delete">Delete</button> => </form> %>Sean Doyle
-
Change
ActionView::Helpers::UrlHelper#button_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_tag
andjavascript_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::ModuleSerializer
if 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 methods
assert_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 an
ActiveJob::EnqueueErrorwhich will be caught and stored in the job
instance so code attempting to enqueue jobs can inspect any raised
EnqueueErrorusing 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 = niluser.password # => 'something'
Now:
user.password = 'something'
user.password = niluser.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 remainednilAndres 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 detects
inverse_of: :post, so we don't need to pass that option:class Post < ActiveRecord::Base has_many :comments, -> { visible } end class Comment < ActiveRecord::Base belongs_to :post endNote that the automatic detection still won't work if the inverse
association has a scope. In this example a scope on thepostassociation
would still prevent Rails from finding the inverse for thecomments
association.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 using
SET 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_timestamp
for the SQL to produce a high precision timestamp on the current database.Fixes #42992
Sam Bostock
-
Add ssl support for postgresql database tasks
Add
PGSSLMODE,PGSSLCERT,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#update
and not also to the callbacks from the update itself.Dylan Thacker-Smith
-
Fix 2 cases that inferred polymorphic class from the association's
foreign_type
usingString#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, andindexes
would behave differently than one another when a table didn't exist and differently across
database adapters. This change unifies the behavior so each method behaves the same regardless
of adapter.The behavior now is:
columns: (unchanged) raises a db error if the table does not exist.
columns_hash: (unchanged) raises a db error if the table does not exist.
primary_keys: (unchanged) 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 optiondatabase_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 theschema_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_columns
to stop using it.Jean Boussier
-
Rails can now verify foreign keys after loading fixtures in tests.
This will be the default for new apps in Rails 7. To opt in:
config.active_record.verify_foreign_keys_for_fixtures = 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 likerails 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_encryption
that 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 from
add_column. This means that migrations adding a duplicate column with a different type will no
longer raise an error.Eileen M. Uchitelle
-
Log a warning message when running SQLite in production.
Using SQLite in production ENV is generally discouraged. SQLite is also the default adapter
in a new Rails application.
For the above reasons log a warning message when running SQLite in production.The warning can be disabled by setting
config.active_record.sqlite3_production_warning=false.Jacopo Beschi
-
Add option to disable joins for
has_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 forhas_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 visiting
Arel::Nodes::SelectCore,SelectStatement,InsertStatement,UpdateStatement, and
DeleteStatement, 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 wildcardSELECT *queries, which invalidates the result
of cached prepared statements and raises aPreparedStatementCacheExpirederror.When enabled, Active Record will avoid wildcards and always include column names
inSELECTqueries, 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 use
quoted_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. Usingn_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 setasync_query_executor
tonilwhich 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 define
config.active_record.global_executor_concurrency. This defaults to 4. For applications that want
to have a thread pool for each database connection,config.active_record.async_query_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 configured
NATIVE_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
namedApplicationRecordcan 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 callconnects_to
needs 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 adapterActiveRecord::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 account
primary_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) on
has_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 to
trueif 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 to
trueif 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 makes
ActiveStorage::VariantRecordconsistent withActiveStorage::BlobandActiveStorage::Attachment
that 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_proxy
rails_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::Duration
ignored 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 the
ActiveSupport::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 totrue
and is the default for new apps.The old behavior is the default for upgraded apps and will output a
deprecation warning every time a value that is different than one of
the constants defined on theDigest::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_exception
to allow these to be thrown.Nicholas A. Stuart
-
Allow entirely opting out of deprecation warnings.
Previously if you did
app.config.active_support.deprecation = :silence, some work would
still be done on each call 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:year
and: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 the
RAILS_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_str
to 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 as
Rails.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.0or
config.load_defaults 7.0. Regardless of the configuration Active Support
7.0 can read cache entries serialized by Active Support 6.1 which allows to
upgrade without invalidating the cache. However Rails 6.1 can't read the
new format, so all readers must be upgraded before the new format is enabled.Jean Boussier
-
Add
Enumerable#sole, 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. Matches
String#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.rb
orconfig/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 theRails.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 ato_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
thatconfig.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 compatibility
Rails.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
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 7.0.0.rc3
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Allow localhost with a port by default in development
[Fixes: #43864]
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 7.0.0.rc2
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix X_FORWARDED_HOST protection. [CVE-2021-44528]
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.1.4.4
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix issue with host protection not allowing host with port in development.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.1.4.3
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Allow localhost with a port by default in development
[Fixes: #43864]
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.1.4.2
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix X_FORWARDED_HOST protection. [CVE-2021-44528]
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.0.4.4
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix issue with host protection not allowing host with port in development.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.0.4.3
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix issue with host protection not allowing localhost in development.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
-
Allow localhost with a port by default in development
[Fixes: #43864]
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.0.4.2
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- Fix X_FORWARDED_HOST protection. [CVE-2021-44528]
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 7.0.0.rc1
Active Support
-
Deprecate passing a format to
#to_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 the
ActiveSupport::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 totrue
and is the default for new apps.The old behavior is the default for upgraded apps and will output a
deprecation warning every time a value that is different than one of
the constants defined on theDigest::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
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 = niluser.password # => 'something'
Now:
user.password = 'something'
user.password = niluser.password # => nil
Markus Doits
Active Record
-
Remove deprecated
ActiveRecord::DatabaseConfigurations::DatabaseConfig#spec_name.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Connection#in_clause_length.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Connection#allowed_index_name_length.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Base#remove_connection.Rafael Mendonça França
-
Load STI Models in fixtures
Data from Fixtures now loads based on the specific class for models with
Single Table Inheritance. This affects enums defined in subclasses, previously
the value of these fields was not parsed and remainednilAndres 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 detects
inverse_of: :post, so we don't need to pass that option:class Post < ActiveRecord::Base has_many :comments, -> { visible } end class Comment < ActiveRecord::Base belongs_to :post endNote that the automatic detection still won't work if the inverse
association has a scope. In this example a scope on thepostassociation
would still prevent Rails from finding the inverse for thecomments
association.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: -
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 using
SET 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
Action View
-
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 the
FormBuilder#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 the
ActionView::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
Profile
model 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
Action Pack
-
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
aNo 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 the
config.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
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::ModuleSerializer
if the module name is not present.Veerpal Brar
Action Mailer
-
Remove deprecated
ActionMailer::DeliveryJobandActionMailer::Parameterized::DeliveryJob
in favor ofActionMailer::MailDeliveryJob.Rafael Mendonça França
-
email_address_with_namereturns just the address if name is blank.Thomas Hutterer
Action Cable
-
The Action Cable client now ensures successful channel subscriptions:
- The client maintains a set of pending subscriptions until either
the server confirms the subscription or the channel is torn down. - Rectifies the race condition where an unsubscribe is rapidly followed
by a subscribe (on the same channel identifier) and the requests are
handled out of order by the ActionCable server, thereby ignoring the
subscribe command.
Daniel Spinosa
- The client maintains a set of pending subscriptions until either
Active Storage
-
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
Action Mailbox
-
Removed deprecated environment variable
MAILGUN_INGRESS_API_KEY.Rafael Mendonça França
-
Removed deprecated
Rails.application.credentials.action_mailbox.mailgun_api_key.Rafael Mendonça França
Action Text
-
Fix an issue with how nested lists were displayed when converting to plain text
Matt Swanson
-
Allow passing in a custom
direct_upload_urlorblob_url_templatetorich_text_area_tag.Lucas Mansur
Railties
-
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
- Ruby
Published by rafaelfranca over 4 years ago
https://github.com/rails/rails - 6.1.4
Active Support
-
MemCacheStore: convert any underlying value (including
false) to 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 use
quoted_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 setstrict_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 though
strict_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 compatibility
Rails.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
- Ruby
Published by rafaelfranca about 5 years ago
https://github.com/rails/rails - 6.0.4
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_alland
ActiveRecord::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 unnecessaryActiveRecord::StaleObjectError
upon 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 methodFixes #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 configurlsafe_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 when
action_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
- Ruby
Published by rafaelfranca about 5 years ago
https://github.com/rails/rails - 6.1.3.2
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Prevent open redirects by correctly escaping the host allow list
CVE-2021-22903 -
Prevent catastrophic backtracking during mime parsing
CVE-2021-22902 -
Prevent regex DoS in HTTP token authentication
CVE-2021-22904 -
Prevent string polymorphic route arguments.
url_forsupports building polymorphic URLs via an array
of arguments (usually symbols and records). If a developer passes a
user input array, strings can result in unwanted route helper calls.CVE-2021-22885
Gannon McGibbon
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca about 5 years ago
https://github.com/rails/rails - 6.0.3.7
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Prevent catastrophic backtracking during mime parsing
CVE-2021-22902 -
Prevent regex DoS in HTTP token authentication
CVE-2021-22904 -
Prevent string polymorphic route arguments.
url_forsupports building polymorphic URLs via an array
of arguments (usually symbols and records). If a developer passes a
user input array, strings can result in unwanted route helper calls.CVE-2021-22885
Gannon McGibbon
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca about 5 years ago
https://github.com/rails/rails - 5.2.6
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Accept base64_urlsafe CSRF tokens to make forward compatible.
Base64 strict-encoded CSRF tokens are not inherently websafe, which makes
them difficult to deal with. For example, the common practice of sending
the CSRF token to a browser in a client-readable cookie does not work properly
out of the box: the value has to be url-encoded and decoded to survive transport.In this version, we generate Base64 urlsafe-encoded CSRF tokens, which are inherently
safe to transport. Validation accepts both urlsafe tokens, and strict-encoded
tokens for backwards compatibility.How the tokes are encoded is controllr by the
action_controller.urlsafe_csrf_tokens
config.In Rails 5.2.5, the CSRF token format was accidentally changed to urlsafe-encoded.
Atention: If you already upgraded your application to 5.2.5, set the config
urlsafe_csrf_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.
- Ruby
Published by rafaelfranca about 5 years ago
https://github.com/rails/rails - 5.2.4.6
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Prevent regex DoS in HTTP token authentication
CVE-2021-22904 -
Prevent string polymorphic route arguments.
url_forsupports building polymorphic URLs via an array
of arguments (usually symbols and records). If a developer passes a
user input array, strings can result in unwanted route helper calls.CVE-2021-22885
Gannon McGibbon
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca about 5 years ago
https://github.com/rails/rails - 6.1.3.1
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Marcel is upgraded to version 1.0.0 to avoid a dependency on GPL-licensed mime types data.
George Claghorn
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by georgeclaghorn over 5 years ago
https://github.com/rails/rails - 6.0.3.6
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Marcel is upgraded to version 1.0.0 to avoid a dependency on GPL-licensed mime types data.
George Claghorn
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by georgeclaghorn over 5 years ago
https://github.com/rails/rails - 5.2.5
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Marcel is upgraded to version 1.0.0 to avoid a dependency on GPL-licensed mime types data.
George Claghorn
Railties
- No changes.
- Ruby
Published by georgeclaghorn over 5 years ago
https://github.com/rails/rails - 6.1.3
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Fix the MySQL adapter to always set the right collation and charset
to the connection session.Rafael Mendonça França
-
Fix MySQL adapter handling of time objects when prepared statements
are enabled.Rafael Mendonça França
-
Fix scoping in enum fields using conditions that would generate
anINclause.Ryuta Kamizono
-
Skip optimised #exist? query when #include? is called on a relation
with a having clauseRelations that have aliased select values AND a having clause that
references an aliased select value would generate an error when
#include? was called, due to an optimisation that would generate
call #exists? on the relation instead, which effectively alters
the select values of the query (and thus removes the aliased select
values), but leaves the having clause intact. Because the having
clause is then referencing an aliased column that is no longer
present in the simplified query, an ActiveRecord::InvalidStatement
error was raised.An sample query affected by this problem:
Author.select('COUNT(*) as total_posts', 'authors.*') .joins(:posts) .group(:id) .having('total_posts > 2') .include?(Author.first)This change adds an addition check to the condition that skips the
simplified #exists? query, which simply checks for the presence of
a having clause.Fixes #41417
Michael Smart
-
Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted
without Rails knowledge (e.g., if app gets kill -9d during long-running query or due to Rack::Timeout), app won't end
up in perpetual crash state for being inconsistent with Postgres.wbharding, Martin Tepper
Action View
- No changes.
Action Pack
-
Re-define routes when not set correctly via inheritance.
John Hawthorn
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 6.1.2.1
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Fix possible DoS vector in PostgreSQL money type
Carefully crafted input can cause a DoS via the regular expressions used
for validating the money format in the PostgreSQL adapter. This patch
fixes the regexp.Thanks to @dee-see from Hackerone for this patch!
[CVE-2021-22880]
Aaron Patterson
Action View
- No changes.
Action Pack
-
Prevent open redirect when allowed host starts with a dot
[CVE-2021-22881]
Thanks to @tktech (https://hackerone.com/tktech) for reporting this
issue and the patch!Aaron Patterson
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 6.0.3.5
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Fix possible DoS vector in PostgreSQL money type
Carefully crafted input can cause a DoS via the regular expressions used
for validating the money format in the PostgreSQL adapter. This patch
fixes the regexp.Thanks to @dee-see from Hackerone for this patch!
[CVE-2021-22880]
Aaron Patterson
Action View
- No changes.
Action Pack
-
Prevent open redirect when allowed host starts with a dot
[CVE-2021-22881]
Thanks to @tktech (https://hackerone.com/tktech) for reporting this
issue and the patch!Aaron Patterson
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 5.2.4.5
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Fix possible DoS vector in PostgreSQL money type
Carefully crafted input can cause a DoS via the regular expressions used
for validating the money format in the PostgreSQL adapter. This patch
fixes the regexp.Thanks to @dee-see from Hackerone for this patch!
[CVE-2021-22880]
Aaron Patterson
Action View
- No changes.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 6.1.2
Active Support
-
ActiveSupport::Cache::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.
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 6.1.1
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_tag
andjavascript_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
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 6.1.0
Active Support
-
Ensure
MemoryStoredisables compression by default. Reverts behavior of
MemoryStoreto 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 using
OpenSSL.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. Use
URI::DEFAULT_PARSERinstead.Jean Boussier
-
require_dependencyhas been documented to be obsolete in:zeitwerk
mode. The method is not deprecated as such (yet), but applications are
encouraged to not use it.In
: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 the
ActiveSupport.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.rbSee 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 when
ActiveSupport.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 of
ActiveSupport::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, likeerrors#firstwill returnActiveModel::Errorand manipulating
errors.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
endAfter:
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
endEileen 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_length
table_name_length
columns_per_table
indexes_per_table
columns_per_multicolumn_index
sql_query_length
joins_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.fetch
each
first
values
[]=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 usingconfig.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 to
ActiveSupport::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 than
ActiveRecord::StatementInvalidwhen they encounter a connection error.Jean Boussier
-
Mysql2Adapter#quote_stringnow raisesActiveRecord::ConnectionNotEstablishedrather than
ActiveRecord::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
bystore_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 extend
rails 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, userelation.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_alland
ActiveRecord::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 unnecessaryActiveRecord::StaleObjectError
upon 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:loadand
rails 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 methodFixes #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
settingconfig.action_view.form_with_generates_remote_formstotrue.Petrik de Heus
-
Yield translated strings to calls of
ActionView::FormBuilder#button
when a block is given.Sean Doyle
-
Alias
ActionView::Helpers::Tags::Label::LabelBuilder#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
DOMTokenList
values. This is useful when declaring lists of label text identifiers in
aria-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 of
config.i18n.raise_on_missing_translations.New generalized configuration option now determines whether an error should be raised
for missing translations in controllers and views.fatkodima
-
Instrument layout rendering in
TemplateRenderer#render_with_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 theDEBUGlevel 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#GETand
ActionDispatch::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, with
Content-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 throughconfig.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::Parameters
without 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 withString#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 when
Rails.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:marshal
to:hybridor the server changesuse_authenticated_cookie_encryption
fromfalsetotrue, 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 withtmp: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 instance
remote_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'Accept
header to determine what to return. And if we don't addVary
in the response header, browsers might accidentally cache different
types of content, which would cause issues: e.g. javascript got displayed
instead of html content. This PR fixes these issues by addingVary: Accept
in these types of requests. For more detailed problem description, please read:https://github.com/rails/rails/pull/36213
Fixes #25842.
Stan Lo
-
Fix IntegrationTest
follow_redirect!to follow redirection using the same HTTP verb when following
a 307 redirection.Edouard Chin
-
System tests require Capybara 3.26 or newer.
George Claghorn
-
Reduced log noise handling ActionController::RoutingErrors.
Alberto Fernández-Capel
-
Add DSL for configuring HTTP Feature Policy.
This new DSL provides a way to configure an HTTP Feature Policy at a
global or per-controller level. Full details of HTTP Feature Policy
specification and guidelines can be found at MDN:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy
Example global policy:
Rails.application.config.feature_policy do |f| f.camera :none f.gyroscope :none f.microphone :none f.usb :none f.fullscreen :self f.payment :self, "https://secure.example.com" 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 with
assert_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 file
config.active_job.skip_after_callbacks_if_terminated = true.Edouard Chin
-
Fix enqueuing and performing incorrect logging message.
Jobs will no longer always log "Enqueued MyJob" or "Performed MyJob" when they actually didn't get enqueued/performed.
class MyJob < ApplicationJob before_enqueue { throw(:abort) } end MyJob.perform_later # Will no longer log "Enqueued MyJob" since job wasn't even enqueued through adapter.A new message will be logged in case a job couldn't be enqueued, either because the callback chain was halted or
because an exception happened during enqueuing. (i.e. Redis is down when you try to enqueue your job)Edouard Chin
-
Add an option to disable logging of the job arguments when enqueuing and executing the job.
class SensitiveJob < ApplicationJob self.log_arguments = false def perform(my_sensitive_argument) end 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 customidincable.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 therails_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 a
service_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 key
public: 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 a
MiniMagick::Error, which caused persistentActiveStorage::AnalyzeJob
failures. It now logs the error and returns{}, resulting in no metadata
being added to the offending image blob.George Claghorn
-
Method calls on singular attachments return
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 appropriate
aria-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/railsrcif
XDG_CONFIG_HOMEis not set). If this file does not exist,rails new
will fall back to~/.railsrc.The fallback behaviour means this does not cause any breaking changes.
Nick Wolf
-
Change the default logging level from :debug to :info to avoid inadvertent exposure of personally
identifiable information (PII) in production environments.Eric M. Payne
-
Automatically generate abstract class when using multiple databases.
When generating a scaffold for a multiple database application, Rails will now automatically generate the abstract class for the database when the database argument is passed. This abstract class will include the connection information for the writing configuration and any models generated for that database will automatically inherit from the abstract class.
Usage:
$ bin/rails generate scaffold Pet name:string --database=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 before
ActionDispatch::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, and
eager_load_paths.As a consequence, applications cannot autoload within those files. Before, they technically could, but changes in autoloaded classes or modules had no effect anyway in the configuration because reloading does not reboot.
Ways to use application code in these files:
-
Define early in the boot process a class that is not reloadable, from which the application takes configuration values that get passed to the framework.
# In config/application.rb, for example. require "#{Rails.root}/lib/my_app/config" # In config/environments/development.rb, for example. config.foo = MyApp::Config.foo -
If the class has to be reloadable, then wrap the configuration code in a
to_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
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 6.1.0.rc2
Active Support
-
Ensure
MemoryStoredisables compression by default. Reverts behavior of
MemoryStoreto its prior rails5.1behavior.Max Gurewitz
Active Model
- No changes.
Active Record
-
Fix odd behavior of inverse_of with multiple belongs_to to same class.
Fixes #35204.
Tomoyuki Kai
-
Build predicate conditions with objects that delegate
#idand primary key:class AdminAuthor delegate_missing_to :@author def initialize(author) @author = author end end Post.where(author: AdminAuthor.new(author))Sean Doyle
Action View
-
Change form_with to generate non-remote forms by default.
form_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
settingconfig.action_view.form_with_generates_remote_formstotrue.Petrik de Heus
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
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
-
Implement
strict_loadingon ActiveStorage associations.David Angulo
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 6.1.0.rc1
Active Support
-
Calling
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 using
OpenSSL.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. Use
URI::DEFAULT_PARSERinstead.Jean Boussier
-
require_dependencyhas been documented to be obsolete in:zeitwerk
mode. The method is not deprecated as such (yet), but applications are
encouraged to not use it.In
: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 the
ActiveSupport.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.rbSee 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 when
ActiveSupport.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 of
ActiveSupport::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, likeerrors#firstwill returnActiveModel::Errorand manipulating
errors.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
-
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
endAfter:
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
endEileen 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_length
table_name_length
columns_per_table
indexes_per_table
columns_per_multicolumn_index
sql_query_length
joins_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 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.fetch
each
first
values
[]=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 usingconfig.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 to
ActiveSupport::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 than
ActiveRecord::StatementInvalidwhen they encounter a connection error.Jean Boussier
-
Mysql2Adapter#quote_stringnow raisesActiveRecord::ConnectionNotEstablishedrather than
ActiveRecord::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
bystore_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 extend
rails 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, userelation.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_alland
ActiveRecord::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 unnecessaryActiveRecord::StaleObjectError
upon 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.
p Knot.create => #<Knot id: 1, created_at: "2016-05-05 01:29:47.116928000">akinomaeni
-
Deprecate passing a column to
type_cast.Ryuta Kamizono
-
Deprecate
in_clause_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:loadand
rails 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
-
Yield translated strings to calls of
ActionView::FormBuilder#button
when 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
DOMTokenList
values. This is useful when declaring lists of label text identifiers in
aria-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 of
config.i18n.raise_on_missing_translations.New generalized configuration option now determines whether an error should be raised
for missing translations in controllers and views.fatkodima
-
Instrument layout rendering in
TemplateRenderer#render_with_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 theDEBUGlevel 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
-
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#GETand
ActionDispatch::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, with
Content-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 throughconfig.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::Parameters
without 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 withString#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 when
Rails.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:marshal
to:hybridor the server changesuse_authenticated_cookie_encryption
fromfalsetotrue, 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 withtmp: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 instance
remote_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'Accept
header to determine what to return. And if we don't addVary
in the response header, browsers might accidentally cache different
types of content, which would cause issues: e.g. javascript got displayed
instead of html content. This PR fixes these issues by addingVary: Accept
in these types of requests. For more detailed problem description, please read:https://github.com/rails/rails/pull/36213
Fixes #25842.
Stan Lo
-
Fix IntegrationTest
follow_redirect!to follow redirection using the same HTTP verb when following
a 307 redirection.Edouard Chin
-
System tests require Capybara 3.26 or newer.
George Claghorn
-
Reduced log noise handling ActionController::RoutingErrors.
Alberto Fernández-Capel
-
Add DSL for configuring HTTP Feature Policy.
This new DSL provides a way to configure an HTTP Feature Policy at a
global or per-controller level. Full details of HTTP Feature Policy
specification and guidelines can be found at MDN:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy
Example global policy:
Rails.application.config.feature_policy do |f| f.camera :none f.gyroscope :none f.microphone :none f.usb :none f.fullscreen :self f.payment :self, "https://secure.example.com" 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 with
assert_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 file
config.active_job.skip_after_callbacks_if_terminated = true.Edouard Chin
-
Fix enqueuing and performing incorrect logging message.
Jobs will no longer always log "Enqueued MyJob" or "Performed MyJob" when they actually didn't get enqueued/performed.
class MyJob < ApplicationJob before_enqueue { throw(:abort) } end MyJob.perform_later # Will no longer log "Enqueued MyJob" since job wasn't even enqueued through adapter.A new message will be logged in case a job couldn't be enqueued, either because the callback chain was halted or
because an exception happened during enqueing. (i.e. Redis is down when you try to enqueue your job)Edouard Chin
-
Add an option to disable logging of the job arguments when enqueuing and executing the job.
class SensitiveJob < ApplicationJob self.log_arguments = false def perform(my_sensitive_argument) end 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
-
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 customidincable.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
-
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 therails_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 a
service_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 key
public: 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 a
MiniMagick::Error, which caused persistentActiveStorage::AnalyzeJob
failures. It now logs the error and returns{}, resulting in no metadata
being added to the offending image blob.George Claghorn
-
Method calls on singular attachments return
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
-
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 appropriate
aria-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/railsrcif
XDG_CONFIG_HOMEis not set). If this file does not exist,rails new
will fall back to~/.railsrc.The fallback behaviour means this does not cause any breaking changes.
Nick Wolf
-
Change the default logging level from :debug to :info to avoid inadvertent exposure of personally
identifiable information (PII) in production environments.Eric M. Payne
-
Automatically generate abstract class when using multiple databases.
When generating a scaffold for a multiple database application, Rails will now automatically generate the abstract class for the database when the database argument is passed. This abstract class will include the connection information for the writing configuration and any models generated for that database will automatically inherit from the abstract class.
Usage:
$ bin/rails generate scaffold Pet name:string --database=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 before
ActionDispatch::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, and
eager_load_paths.As a consequence, applications cannot autoload within those files. Before, they technically could, but changes in autoloaded classes or modules had no effect anyway in the configuration because reloading does not reboot.
Ways to use application code in these files:
-
Define early in the boot process a class that is not reloadable, from which the application takes configuration values that get passed to the framework.
# In config/application.rb, for example. require "#{Rails.root}/lib/my_app/config" # In config/environments/development.rb, for example. config.foo = MyApp::Config.foo -
If the class has to be reloadable, then wrap the configuration code in a
to_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
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 6.0.3.4
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- [CVE-2020-8264] Prevent XSS in Actionable Exceptions
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 5 years ago
https://github.com/rails/rails - 6.0.3.3
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- [CVE-2020-8185] Fix potential XSS vulnerability in the
translate/thelper.
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca almost 6 years ago
https://github.com/rails/rails - 5.2.4.4
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- [CVE-2020-15169] Fix potential XSS vulnerability in the
translate/thelper
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca almost 6 years ago
https://github.com/rails/rails - 6.0.3.2
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
- [CVE-2020-8185] Only allow ActionableErrors if show_detailed_exceptions is enabled
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca almost 6 years ago
https://github.com/rails/rails - 6.0.3.1
Active Support
-
[CVE-2020-8165] Deprecate Marshal.load on raw cache read in RedisCacheStore
-
[CVE-2020-8165] Avoid Marshal.load on raw cache value in MemCacheStore
Active Model
- No changes.
Active Record
- No changes.
Action View
- [CVE-2020-8167] Check that request is same-origin prior to including CSRF token in XHRs
Action Pack
-
[CVE-2020-8166] HMAC raw CSRF token before masking it, so it cannot be used to reconstruct a per-form token
-
[CVE-2020-8164] Return self when calling #each, #each_pair, and #each_value instead of the raw @parameters hash
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- [CVE-2020-8162] Include Content-Length in signature for ActiveStorage direct upload
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca about 6 years ago
https://github.com/rails/rails - 4.2.11.3
Action Mailer
- No changes.
Action Pack
- No changes.
Action View
- Backport a missing commit for [CVE-2020-8163]
Active Job
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Active Support
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca about 6 years ago
https://github.com/rails/rails - 4.2.11.2
Action Mailer
- No changes.
Action Pack
- No changes.
Action View
- Restrict local variable names in templates [CVE-2020-8163]
Active Job
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Active Support
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca about 6 years ago
https://github.com/rails/rails - 5.2.4.3
Active Support
-
[CVE-2020-8165] Deprecate Marshal.load on raw cache read in RedisCacheStore
-
[CVE-2020-8165] Avoid Marshal.load on raw cache value in MemCacheStore
Active Model
- No changes.
Active Record
- No changes.
Action View
- [CVE-2020-8167] Check that request is same-origin prior to including CSRF token in XHRs
Action Pack
-
[CVE-2020-8166] HMAC raw CSRF token before masking it, so it cannot be used to reconstruct a per-form token
-
[CVE-2020-8164] Return self when calling #each, #each_pair, and #each_value instead of the raw @parameters hash
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- [CVE-2020-8162] Include Content-Length in signature for ActiveStorage direct upload
Railties
- No changes.
- Ruby
Published by rafaelfranca about 6 years ago
https://github.com/rails/rails - 6.0.3
In this version, we fixed warnings when used with Ruby 2.7 across the entire framework.
Following are the list of other changes, per-framework.
Active Support
-
Array#to_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 when
ActiveSupport.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 with
assert_enqueued_with.Dmitry Polushkin
-
Add queue name support to Que adapter
Brad Nauta, Wojciech Wnętrzak
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
-
Update Mandrill inbound email route to respond appropriately to HEAD requests for URL health checks from Mandrill.
Bill Cromie
Action Text
- No changes.
Railties
-
Cache compiled view templates when running tests by default
When generating a new app without
--skip-spring, caching classes is
disabled 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 added
i18n. These namespaces are only required to respond toeager_load!.Xavier Noria
- Ruby
Published by rafaelfranca about 6 years ago
https://github.com/rails/rails - 6.0.3.rc1
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 when
ActiveSupport.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 with
assert_enqueued_with.Dmitry Polushkin
-
Add queue name support to Que adapter
Brad Nauta, Wojciech Wnętrzak
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
-
Update Mandrill inbound email route to respond appropriately to HEAD requests for URL health checks from Mandrill.
Bill Cromie
Action Text
- No changes.
Railties
-
Cache compiled view templates when running tests by default
When generating a new app without
--skip-spring, caching classes is
disabled 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 added
i18n. These namespaces are only required to respond toeager_load!.Xavier Noria
- Ruby
Published by rafaelfranca about 6 years ago
https://github.com/rails/rails - 6.0.2.2
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
-
Fix possible XSS vector in escape_javascript helper
CVE-2020-5267
Aaron Patterson
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 6 years ago
https://github.com/rails/rails - 5.2.4.2
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
-
Fix possible XSS vector in
escape_javascripthelperCVE-2020-5267
Aaron Patterson
Action Pack
- No changes.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 6 years ago
https://github.com/rails/rails - 6.0.2.1
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Fix possible information leak / session hijacking vulnerability.
The
ActionDispatch::Session::MemcacheStoreis still vulnerable given it requires the
gem dalli to be updated as well.CVE-2019-16782.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Action Mailbox
- No changes.
Action Text
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 6 years ago
https://github.com/rails/rails - 5.2.4.1
Active Support
- No changes.
Active Model
- No changes.
Active Record
- No changes.
Action View
- No changes.
Action Pack
-
Fix possible information leak / session hijacking vulnerability.
The
ActionDispatch::Session::MemcacheStoreis still vulnerable given it requires the
gem dalli to be updated as well.CVE-2019-16782.
Active Job
- No changes.
Action Mailer
- No changes.
Action Cable
- No changes.
Active Storage
- No changes.
Railties
- No changes.
- Ruby
Published by rafaelfranca over 6 years ago
https://github.com/rails/rails - 6.0.2
Active Support
-
Eager load translations during initialization.
Diego Plentz
-
Use per-thread CPU time clock on
ActiveSupport::Notifications.George Claghorn
Active Model
- No changes.
Active Record
-
Share the same connection pool for primary and replica databases in the
transactional tests for the same database.Edouard Chin
-
Fix the preloader when one record is fetched using
after_initialize
but not the entire collection.Bradley Price
-
Fix collection callbacks not terminating when
: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 likewhere.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 runEdouard 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
- Ruby
Published by rafaelfranca over 6 years ago
https://github.com/rails/rails - 6.0.2.rc2
Active Support
-
Eager load translations during initialization.
Diego Plentz
-
Use per-thread CPU time clock on
ActiveSupport::Notifications.George Claghorn
Active Model
- No changes.
Active Record
-
Share the same connection pool for primary and replica databases in the
transactional tests for the same database.Edouard Chin
-
Fix the preloader when one record is fetched using
after_initialize
but not the entire collection.Bradley Price
-
Fix collection callbacks not terminating when
: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 likewhere.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 runEdouard 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
- Ruby
Published by rafaelfranca over 6 years ago
https://github.com/rails/rails - 5.2.4
Active Support
-
Make ActiveSupport::Logger Fiber-safe. Fixes #36752.
Use
Fiber.current.__id__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: true
associations, 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 the
belongs_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 in
before_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 byRails.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
- Ruby
Published by rafaelfranca over 6 years ago
https://github.com/rails/rails - 6.0.2.rc1
Active Support
-
Eager load translations during initialization.
Diego Plentz
-
Use per-thread CPU time clock on
ActiveSupport::Notifications.George Claghorn
Active Model
- No changes.
Active Record
-
Share the same connection pool for primary and replica databases in the
transactional tests for the same database.Edouard Chin
-
Fix the preloader when one record is fetched using
after_initialize
but not the entire colection.Bradley Price
-
Fix collection callbacks not terminating when
: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 likewhere.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 runEdouard 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
-
Configuration files for environments (
config/environments/*.rb) are
now able to modifyautoload_paths,autoload_once_paths, and
eager_load_paths.Allen Hsu & Xavier Noria
- Ruby
Published by rafaelfranca over 6 years ago
https://github.com/rails/rails - 5.2.4.rc1
Active Support
-
Make ActiveSupport::Logger Fiber-safe. Fixes #36752.
Use
Fiber.current.__id__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: true
associations, 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 the
belongs_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 in
before_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 byRails.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
- Ruby
Published by rafaelfranca over 6 years ago
https://github.com/rails/rails - 6.0.1
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
- Ruby
Published by georgeclaghorn over 6 years ago
https://github.com/rails/rails - 6.0.1.rc1
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#reload
is 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::TestCase
rather 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
- Ruby
Published by georgeclaghorn over 6 years ago
https://github.com/rails/rails - 5.2.3
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?and
Range#===.Range#===works correctly on Ruby 2.6.Range#include?is moved
into a new file, with these two methods.utilum
-
If the same block is
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
BigDecimalandFloat
by 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 keeppublic
header 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
- Ruby
Published by rafaelfranca over 7 years ago
https://github.com/rails/rails - 5.1.7
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Fix
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 that
to_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.
- Ruby
Published by rafaelfranca over 7 years ago
https://github.com/rails/rails - 5.1.7.rc1
Active Support
- No changes.
Active Model
- No changes.
Active Record
-
Fix
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 that
to_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.
- Ruby
Published by rafaelfranca over 7 years ago
https://github.com/rails/rails - 5.2.3.rc1
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?and
Range#===.Range#===works correctly on Ruby 2.6.Range#include?is moved
into a new file, with these two methods.utilum
-
If the same block is
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
BigDecimalandFloat
by 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 keeppublic
header 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
- Ruby
Published by rafaelfranca over 7 years ago
https://github.com/rails/rails - 6.0.0.beta1
Active Support
-
Remove deprecated
Module#reachable?method.Rafael Mendonça França
-
Remove deprecated
#acronym_regexmethod fromInflections.Rafael Mendonça França
-
Fix
String#safe_constantizethrowing aLoadErrorfor incorrectly cased constant references.Keenan Brock
-
Preserve key order passed to
ActiveSupport::CacheStore#fetch_multi.fetch_multi(*names)now returns its results in the same order as the*namesrequested, rather than returning cache hits followed by cache misses.Gannon McGibbon
-
If the same block is
includedmultiple times for a Concern, an exception is no longer raised.Mark J. Titorenko, Vlad Bokov
-
Fix bug where
#to_optionsforActiveSupport::HashWithIndifferentAccess
would not act as alias for#symbolize_keys.Nick Weiland
-
Improve the logic that detects non-autoloaded constants.
Jan Habermann, Xavier Noria
-
Deprecate
ActiveSupport::Multibyte::Unicode#pack_graphemes(array)andActiveSuppport::Multibyte::Unicode#unpack_graphemes(string)
in favor ofarray.flatten.pack("U*")andstring.scan(/\X/).map(&:codepoints), respectively.Francesco Rodríguez
-
Deprecate
ActiveSupport::Multibyte::Chars.consumes?in favor ofString#is_utf8?.Francesco Rodríguez
-
Fix duration being rounded to a full second.
time = DateTime.parse("2018-1-1") time += 0.51.secondsWill now correctly add 0.51 second and not 1 full second.
Edouard Chin
-
Deprecate
ActiveSupport::Multibyte::Unicode#normalizeandActiveSuppport::Multibyte::Chars#normalize
in favor ofString#unicode_normalizeFrancesco Rodríguez
-
Deprecate
ActiveSupport::Multibyte::Unicode#downcase/upcase/swapcasein favor of
String#downcase/upcase/swapcase.Francesco Rodríguez
-
Add
ActiveSupport::ParameterFilter.Yoshiyuki Kinjo
-
Rename
Module#parent,Module#parents, andModule#parent_nameto
module_parent,module_parents, andmodule_parent_name.Gannon McGibbon
-
Deprecate the use of
LoggerSilencein favor ofActiveSupport::LoggerSilenceEdouard Chin
-
Deprecate using negative limits in
String#firstandString#last.Gannon McGibbon, Eric Turner
-
Fix bug where
#withoutforActiveSupport::HashWithIndifferentAccesswould fail
with symbol argumentsAbraham Chan
-
Treat
#delete_prefix,#delete_suffixand#unicode_normalizeresults as non-html_safe.
Ensure safety of arguments for#insert,#[]=and#replacecalls onhtml_safeStrings.Janosch Müller
-
Changed
ActiveSupport::TaggedLogging.newto return a new logger instance instead
of mutating the one received as parameter.Thierry Joyal
-
Define
unfreeze_timeas an alias oftravel_backinActiveSupport::Testing::TimeHelpers.The alias is provided for symmetry with
freeze_time.Ryan Davidson
-
Add support for tracing constant autoloads. Just throw
ActiveSupport::Dependencies.logger = Rails.logger ActiveSupport::Dependencies.verbose = truein an initializer.
Xavier Noria
-
Maintain
html_safe?on html_safe strings when sliced.string = "<div>test</div>".html_safe string[-1..1].html_safe? # => trueElom Gomez, Yumin Wong
-
Add
Array#extract!.The method removes and returns the elements for which the block returns a true value.
If no block is given, an Enumerator is returned instead.numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9] numbers # => [0, 2, 4, 6, 8]bogdanvlviv
-
Support not to cache
nilforActiveSupport::Cache#fetch.cache.fetch('bar', skip_nil: true) { nil } cache.exist?('bar') # => falseMartin Hong
-
Add "event object" support to the notification system.
Before this change, end users were forced to create hand made artisanal
event objects on their own, like this:ActiveSupport::Notifications.subscribe('wait') do |*args| @event = ActiveSupport::Notifications::Event.new(*args) end ActiveSupport::Notifications.instrument('wait') do sleep 1 end @event.duration # => 1000.138After this change, if the block passed to
subscribeonly takes one
parameter, the framework will yield an event object to the block. Now
end users are no longer required to make their own:ActiveSupport::Notifications.subscribe('wait') do |event| @event = event end ActiveSupport::Notifications.instrument('wait') do sleep 1 end p @event.allocations # => 7 p @event.cpu_time # => 0.256 p @event.idle_time # => 1003.2399Now you can enjoy event objects without making them yourself. Neat!
Aaron "t.lo" Patterson
-
Add cpu_time, idle_time, and allocations to Event.
Eileen M. Uchitelle, Aaron Patterson
-
RedisCacheStore: support key expiry in increment/decrement.
Pass
:expires_into#incrementand#decrementto set a Redis EXPIRE on the key.If the key is already set to expire, RedisCacheStore won't extend its expiry.
Rails.cache.increment("some_key", 1, expires_in: 2.minutes)Jason Lee
-
Allow
Range#===andRange#cover?on Range.Range#cover?can now accept a range argument likeRange#include?and
Range#===.Range#===works correctly on Ruby 2.6.Range#include?is moved
into a new file, with these two methods.Requiring active_support/core_ext/range/include_range is now deprecated.
Userequire "active_support/core_ext/range/compare_range"instead.utilum
-
Add
index_withto Enumerable.Allows creating a hash from an enumerable with the value from a passed block
or a default argument.%i( title body ).index_with { |attr| post.public_send(attr) } # => { title: "hey", body: "what's up?" } %i( title body ).index_with(nil) # => { title: nil, body: nil }Closely linked with
index_by, which creates a hash where the keys are extracted from a block.Kasper Timm Hansen
-
Fix bug where
ActiveSupport::Timezone.allwould fail when tzinfo data for
any timezone defined inActiveSupport::TimeZone::MAPPINGis missing.Dominik Sander
-
Redis cache store:
delete_matchedno longer blocks the Redis server.
(Switches from evaled Lua to a batched SCAN + DEL loop.)Gleb Mazovetskiy
-
Fix bug where
ActiveSupport::Cachewill massively inflate the storage
size when compression is enabled (which is true by default). This patch
does not attempt to repair existing data: please manually flush the cache
to clear out the problematic entries.Godfrey Chan
-
Fix bug where
URI.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
-
Add
before?andafter?methods toDate,DateTime,
Time, andTimeWithZone.Nick Holden
-
ActiveSupport::Inflector#ordinalandActiveSupport::Inflector#ordinalizenow support
translations through I18n.# locale/fr.rb { fr: { number: { nth: { ordinals: lambda do |_key, number:, **_options| if number.to_i.abs == 1 'er' else 'e' end end, ordinalized: lambda do |_key, number:, **_options| "#{number}#{ActiveSupport::Inflector.ordinal(number)}" end } } } }Christian Blais
-
Add
:privateoption to ActiveSupport'sModule#delegate
in order to delegate methods as private:class User < ActiveRecord::Base has_one :profile delegate :date_of_birth, to: :profile, private: true def age Date.today.year - date_of_birth.year end end # User.new.age # => 29 # User.new.date_of_birth # => NoMethodError: private method `date_of_birth' called for #<User:0x00000008221340>Tomas Valent
-
String#truncate_bytesto truncate a string to a maximum bytesize without
breaking multibyte characters or grapheme clusters like 👩👩👦👦.Jeremy Daer
-
String#strip_heredocpreserves frozenness."foo".freeze.strip_heredoc.frozen? # => trueFixes that frozen string literals would inadvertently become unfrozen:
# frozen_string_literal: true foo = <<-MSG.strip_heredoc la la la MSG foo.frozen? # => false !??Jeremy Daer
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
-
Adds parallel testing to Rails.
Parallelize your test suite with forked processes or threads.
Eileen M. Uchitelle, Aaron Patterson
Active Model
-
Add
ActiveModel::Errors#of_kind?.bogdanvlviv, Rafael Mendonça França
-
Fix numericality equality validation of
BigDecimalandFloat
by casting toBigDecimalon both ends of the validation.Gannon McGibbon
-
Add
#slice!method toActiveModel::Errors.Daniel López Prat
-
Fix numericality validator to still use value before type cast except Active Record.
Fixes #33651, #33686.
Ryuta Kamizono
-
Fix
ActiveModel::Serializers::JSON#as_jsonmethod for timestamps.Before:
contact = Contact.new(created_at: Time.utc(2006, 8, 1)) contact.as_json["created_at"] # => 2006-08-01 00:00:00 UTCAfter:
contact = Contact.new(created_at: Time.utc(2006, 8, 1)) contact.as_json["created_at"] # => "2006-08-01T00:00:00.000Z"Bogdan Gusiev
-
Allows configurable attribute name for
#has_secure_password. This
still defaults to an attribute named 'password', causing no breaking
change. There is a new method#authenticate_XXXwhere XXX is the
configured attribute name, making the existing#authenticatenow an
alias for this when the attribute is the default 'password'.Example:
class User < ActiveRecord::Base has_secure_password :recovery_password, validations: false end user = User.new() user.recovery_password = "42password" user.recovery_password_digest # => "$2a$04$iOfhwahFymCs5weB3BNH/uX..." user.authenticate_recovery_password('42password') # => userUnathi Chonco
-
Add
config.active_model.i18n_full_messagein order to control whether
thefull_messageerror format can be overridden at the attribute or model
level in the locale files. This isfalseby default.Martin Larochelle
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
Active Record
-
Remove deprecated
#set_statefrom the transaction object.Rafael Mendonça França
-
Remove deprecated
#supports_statement_cache?from the database adapters.Rafael Mendonça França
-
Remove deprecated
#insert_fixturesfrom the database adapters.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::ConnectionAdapters::SQLite3Adapter#valid_alter_table_type?.Rafael Mendonça França
-
Do not allow passing the column name to
sumwhen a block is passed.Rafael Mendonça França
-
Do not allow passing the column name to
countwhen a block is passed.Rafael Mendonça França
-
Remove delegation of missing methods in a relation to arel.
Rafael Mendonça França
-
Remove delegation of missing methods in a relation to private methods of the class.
Rafael Mendonça França
-
Deprecate
config.activerecord.sqlite3.represent_boolean_as_integer.Rafael Mendonça França
-
Change
SQLite3Adapterto always represent boolean values as integers.Rafael Mendonça França
-
Remove ability to specify a timestamp name for
#cache_key.Rafael Mendonça França
-
Remove deprecated
ActiveRecord::Migrator.migrations_path=.Rafael Mendonça França
-
Remove deprecated
expand_hash_conditions_for_aggregates.Rafael Mendonça França
-
Set polymorphic type column to NULL on
dependent: :nullifystrategy.On polymorphic associations both the foreign key and the foreign type columns will be set to NULL.
Laerti Papa
-
Allow permitted instance of
ActionController::Parametersas argument ofActiveRecord::Relation#exists?.Gannon McGibbon
-
Add support for endless ranges introduces in Ruby 2.6.
Greg Navis
-
Deprecate passing
migrations_pathstoconnection.assume_migrated_upto_version.Ryuta Kamizono
-
MySQL:
ROW_FORMAT=DYNAMICcreate table option by default.Since MySQL 5.7.9, the
innodb_default_row_formatoption defines the default row
format for InnoDB tables. The default setting isDYNAMIC.
The row format is required for indexing onvarchar(255)withutf8mb4columns.Ryuta Kamizono
-
Fix join table column quoting with SQLite.
Gannon McGibbon
-
Allow disabling scopes generated by
ActiveRecord.enum.Alfred Dominic
-
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
-
Add the ability to prevent writes to a database for the duration of a block.
Allows the application to prevent writes to a database. This can be useful when
you're building out multiple databases and want to make sure you're not sending
writes when you want a read.If
while_preventing_writesis called and the query is considered a write
query the database will raise an exception regardless of whether the database
user is able to write.This is not meant to be a catch-all for write queries but rather a way to enforce
read-only queries without opening a second connection. One purpose of this is to
catch accidental writes, not all writes.Eileen M. Uchitelle
-
Allow aliased attributes to be used in
#update_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
-
Make the implicit order column configurable.
When calling ordered finder methods such as +first+ or +last+ without an
explicit order clause, ActiveRecord sorts records by primary key. This can
result in unpredictable and surprising behaviour when the primary key is
not an auto-incrementing integer, for example when it's a UUID. This change
makes it possible to override the column used for implicit ordering such
that +first+ and +last+ will return more predictable results.Example:
class Project < ActiveRecord::Base self.implicit_order_column = "created_at" endTekin Suleyman
-
Bump minimum PostgreSQL version to 9.3.
Yasuo Honda
-
Values of enum are frozen, raising an error when attempting to modify them.
Emmanuel Byrd
-
Move
ActiveRecord::StatementInvalidSQL to error property and include binds as separate error property.ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception_classnow requiresbindsto be passed as the last argument.ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exceptionnow requiresmessage,sql, andbindsto be passed as keyword arguments.Subclasses of
ActiveRecord::StatementInvalidmust now providesql:andbinds:arguments tosuper.Example:
class MySubclassedError < ActiveRecord::StatementInvalid def initialize(message, sql:, binds:) super(message, sql: sql, binds: binds) end endGannon McGibbon
-
Add an
:if_not_existsoption tocreate_table.Example:
create_table :posts, if_not_exists: true do |t| t.string :title endThat would execute:
CREATE TABLE IF NOT EXISTS posts ( ... )If the table already exists,
if_not_exists: false(the default) raises an
exception whereasif_not_exists: truedoes nothing.fatkodima, Stefan Kanev
-
Defining an Enum as a Hash with blank key, or as an Array with a blank value, now raises an
ArgumentError.Christophe Maximin
-
Adds support for multiple databases to
rails db:schema:cache:dumpandrails db:schema:cache:clear.Gannon McGibbon
-
update_columnsnow correctly raisesActiveModel::MissingAttributeError
if the attribute does not exist.Sean Griffin
-
Add support for hash and url configs in database hash of
ActiveRecord::Base.connected_to.User.connected_to(database: { writing: "postgres://foo" }) do User.create!(name: "Gannon") end config = { "adapter" => "sqlite3", "database" => "db/readonly.sqlite3" } User.connected_to(database: { reading: config }) do User.count endGannon McGibbon
-
Support default expression for MySQL.
MySQL 8.0.13 and higher supports default value to be a function or expression.
https://dev.mysql.com/doc/refman/8.0/en/create-table.html
Ryuta Kamizono
-
Support expression indexes for MySQL.
MySQL 8.0.13 and higher supports functional key parts that index
expression values rather than column or column prefix values.https://dev.mysql.com/doc/refman/8.0/en/create-index.html
Ryuta Kamizono
-
Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error.
Fixes #33056.
Federico Martinez
-
Add basic API for connection switching to support multiple databases.
- Adds a
connects_tomethod for models to connect to multiple databases. Example:
class AnimalsModel < ApplicationRecord self.abstract_class = true connects_to database: { writing: :animals_primary, reading: :animals_replica } end class Dog < AnimalsModel # connected to both the animals_primary db for writing and the animals_replica for reading end- Adds a
connected_toblock method for switching connection roles or connecting to
a database that the model didn't connect to. Connecting to the database in this block is
useful when you have another defined connection, for exampleslow_replicathat you don't
want to connect to by default but need in the console, or a specific code block.
ActiveRecord::Base.connected_to(role: :reading) do Dog.first # finds dog from replica connected to AnimalsBase Book.first # doesn't have a reading connection, will raise an error endActiveRecord::Base.connected_to(database: :slow_replica) do SlowReplicaModel.first # if the db config has a slow_replica configuration this will be used to do the lookup, otherwise this will throw an exception endEileen M. Uchitelle
- Adds a
-
Enum raises on invalid definition values
When defining a Hash enum it can be easy to use [] instead of {}. This
commit checks that only valid definition values are provided, those can
be a Hash, an array of Symbols or an array of Strings. Otherwise it
raises an ArgumentError.Fixes #33961
Alberto Almagro
-
Reloading associations now clears the Query Cache like
Persistence#reloaddoes.class Post < ActiveRecord::Base has_one :category belongs_to :author has_many :comments end # Each of the following will now clear the query cache. post.reload_category post.reload_author post.comments.reloadChristophe Maximin
-
Added
indexoption forchange_tablemigration helpers.
With this change you can create indexes while adding new
columns into the existing tables.Example:
change_table(:languages) do |t| t.string :country_code, index: true endMehmet Emin İNAÇ
-
Fix
transactionreverting for migrations.Before: Commands inside a
transactionin a reverted migration ran uninverted.
Now: This change fixes that by reverting commands insidetransactionblock.fatkodima, David Verhasselt
-
Raise an error instead of scanning the filesystem root when
fixture_pathis blank.Gannon McGibbon, Max Albrecht
-
Allow
ActiveRecord::Base.configurations=to be set with a symbolized hash.Gannon McGibbon
-
Don't update counter cache unless the record is actually saved.
Fixes #31493, #33113, #33117.
Ryuta Kamizono
-
Deprecate
ActiveRecord::Result#to_hashin favor ofActiveRecord::Result#to_a.Gannon McGibbon, Kevin Cheng
-
SQLite3 adapter supports expression indexes.
create_table :users do |t| t.string :email end add_index :users, 'lower(email)', name: 'index_users_on_email', unique: trueGray Kemmey
-
Allow subclasses to redefine autosave callbacks for associated records.
Fixes #33305.
Andrey Subbota
-
Bump minimum MySQL version to 5.5.8.
Yasuo Honda
-
Use MySQL utf8mb4 character set by default.
utf8mb4character set with 4-Byte encoding supports supplementary characters including emoji.
The previous default 3-Byte encoding character setutf8is not enough to support them.Yasuo Honda
-
Fix duplicated record creation when using nested attributes with
create_with.Darwin Wu
-
Configuration item
config.filter_parameterscould also filter out
sensitive values of database columns when call#inspect.
We also addedActiveRecord::Base::filter_attributes/=in order to
specify sensitive attributes to specific model.Rails.application.config.filter_parameters += [:credit_card_number, /phone/] Account.last.inspect # => #<Account id: 123, name: "DHH", credit_card_number: [FILTERED], telephone_number: [FILTERED] ...> SecureAccount.filter_attributes += [:name] SecureAccount.last.inspect # => #<SecureAccount id: 42, name: [FILTERED], credit_card_number: [FILTERED] ...>Zhang Kang, Yoshiyuki Kinjo
-
Deprecate
column_name_length,table_name_length,columns_per_table,
indexes_per_table,columns_per_multicolumn_index,sql_query_length,
andjoins_per_querymethods inDatabaseLimits.Ryuta Kamizono
-
ActiveRecord::Base.configurationsnow returns an object.ActiveRecord::Base.configurationsused to return a hash, but this
is an inflexible data model. In order to improve multiple-database
handling in Rails, we've changed this to return an object. Some methods
are provided to make the object behave hash-like in order to ease the
transition process. Since most applications don't manipulate the hash
we've decided to add backwards-compatible functionality that will throw
a deprecation warning if used, however callingActiveRecord::Base.configurations
will use the new version internally and externally.For example, the following
database.yml:development: adapter: sqlite3 database: db/development.sqlite3Used to become a hash:
{ "development" => { "adapter" => "sqlite3", "database" => "db/development.sqlite3" } }Is now converted into the following object:
#<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[ #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development", @spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}> ]Iterating over the database configurations has also changed. Instead of
calling hash methods on theconfigurationshash directly, a new methodconfigs_forhas
been provided that allows you to select the correct configuration.env_name, and
spec_namearguments are optional. For example these return an array of
database config objects for the requested environment and a single database config object
will be returned for the requested environment and specification name respectively.ActiveRecord::Base.configurations.configs_for(env_name: "development") ActiveRecord::Base.configurations.configs_for(env_name: "development", spec_name: "primary")Eileen M. Uchitelle, Aaron Patterson
-
Add database configuration to disable advisory locks.
production: adapter: postgresql advisory_locks: falseGuo Xiang
-
SQLite3 adapter
alter_tablemethod restores foreign keys.Yasuo Honda
-
Allow
:to_tableoption toinvert_remove_foreign_key.Example:
remove_foreign_key :accounts, to_table: :owners
Nikolay Epifanov, Rich Chen
-
Add environment & load_config dependency to
bin/rake db:seedto enable
seed load in environments without Rails and custom DB configurationTobias Bielohlawek
-
Fix default value for mysql time types with specified precision.
Nikolay Kondratyev
-
Fix
touchoption to behave consistently withPersistence#touchmethod.Ryuta Kamizono
-
Migrations raise when duplicate column definition.
Fixes #33024.
Federico Martinez
-
Bump minimum SQLite version to 3.8
Yasuo Honda
-
Fix parent record should not get saved with duplicate children records.
Fixes #32940.
Santosh Wadghule
-
Fix logic on disabling commit callbacks so they are not called unexpectedly when errors occur.
Brian Durand
-
Ensure
Associations::CollectionAssociation#sizeandAssociations::CollectionAssociation#empty?
use loaded association ids if present.Graham Turner
-
Add support to preload associations of polymorphic associations when not all the records have the requested associations.
Dana Sherson
-
Add
touch_allmethod toActiveRecord::Relation.Example:
Person.where(name: "David").touch_all(time: Time.new(2020, 5, 16, 0, 0, 0))fatkodima, duggiefresh
-
Add
ActiveRecord::Base.base_class?predicate.Bogdan Gusiev
-
Add custom prefix/suffix options to
ActiveRecord::Store.store_accessor.Tan Huynh, Yukio Mizuta
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
-
Deprecate
update_attributes/!in favor ofupdate/!.Eddie Lebow
-
Add
ActiveRecord::Base.create_or_find_by/!to deal with the SELECT/INSERT race condition in
ActiveRecord::Base.find_or_create_by/!by leaning on unique constraints in the database.DHH
-
Add
Relation#pickas short-hand for single-value plucks.DHH
Action View
-
Remove deprecated
image_althelper.Rafael Mendonça França
-
Fix the need of
#protect_against_forgery?method defined in
ActionView::Basesubclasses. This prevents the use of forms and buttons.Genadi Samokovarov
-
Fix UJS permanently showing disabled text in a[data-remote][data-disable-with] elements within forms.
Fixes #33889Wolfgang Hobmaier
-
Prevent non-primary mouse keys from triggering Rails UJS click handlers.
Firefox fires click events even if the click was triggered by non-primary mouse keys such as right- or scroll-wheel-clicks.
For example, right-clicking a link such as the one described below (with an underlying ajax request registered on click) should not cause that request to occur.<%= link_to 'Remote', remote_path, class: 'remote', remote: true, data: { type: :json } %>Fixes #34541
Wolfgang Hobmaier
-
Prevent
ActionView::TextHelper#word_wrapfrom unexpectedly stripping white space from the left side of lines.For example, given input like this:
This is a paragraph with an initial indent, followed by additional lines that are not indented, and finally terminated with a blockquote: "A pithy saying"Calling
word_wrapshould not trim the indents on the first and last lines.Fixes #34487
Lyle Mullican
-
Add allocations to template rendering instrumentation.
Adds the allocations for template and partial rendering to the server output on render.
Rendered posts/_form.html.erb (Duration: 7.1ms | Allocations: 6004) Rendered posts/new.html.erb within layouts/application (Duration: 8.3ms | Allocations: 6654) Completed 200 OK in 858ms (Views: 848.4ms | ActiveRecord: 0.4ms | Allocations: 1539564)Eileen M. Uchitelle, Aaron Patterson
-
Respect the
only_pathoption passed tourl_forwhen the options are passed in as an arrayFixes #33237.
Joel Ambass
-
Deprecate calling private model methods from view helpers.
For example, in methods like
options_from_collection_for_select
andcollection_selectit is possible to call private methods from
the objects used.Fixes #33546.
Ana María Martínez Gómez
-
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 that
to_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
-
Mark arrays of translations as trusted safe by using the
_htmlsuffix.Example:
en: foo_html: - "One" - "<strong>Two</strong>" - "Three 👋 🙂"Juan Broullon
-
Add
year_formatoption to date_select tag. This option makes it possible to customize year
names. Lambda should be passed to use this option.Example:
date_select('user_birthday', '', start_year: 1998, end_year: 2000, year_format: ->year { "Heisei #{year - 1988}" })The HTML produced:
<select id="user_birthday__1i" name="user_birthday[(1i)]"> <option value="1998">Heisei 10</option> <option value="1999">Heisei 11</option> <option value="2000">Heisei 12</option> </select> /* The rest is omitted */Koki Ryu
-
Fix JavaScript views rendering does not work with Firefox when using
Content Security Policy.Fixes #32577.
Yuji Yaginuma
-
Add the
nonce: trueoption forjavascript_include_taghelper to
support automatic nonce generation for Content Security Policy.
Works the same way asjavascript_tag nonce: truedoes.Yaroslav Markin
-
Remove
ActionView::Helpers::RecordTagHelper.Yoshiyuki Hirano
-
Disable
ActionView::Templatefinalizers in test environment.Template finalization can be expensive in large view test suites.
Add a configuration option,
action_view.finalize_compiled_template_methods, and turn it off in
the test environment.Simon Coffey
-
Extract the
confirmcall in its own, overridable method inrails_ujs.Example:
Rails.confirm = function(message, element) { return (my_bootstrap_modal_confirm(message)); }Mathieu Mahé
-
Enable select tag helper to mark
promptoption asselectedand/ordisabledforrequired
field.Example:
select :post, :category, ["lifestyle", "programming", "spiritual"], { selected: "", disabled: "", prompt: "Choose one" }, { required: true }Placeholder option would be selected and disabled.
The HTML produced:
<select required="required" name="post[category]" id="post_category"> <option disabled="disabled" selected="selected" value="">Choose one</option> <option value="lifestyle">lifestyle</option> <option value="programming">programming</option> <option value="spiritual">spiritual</option></select>Sergey Prikhodko
-
Don't enforce UTF-8 by default.
With the disabling of TLS 1.0 by most major websites, continuing to run
IE8 or lower becomes increasingly difficult so default to not enforcing
UTF-8 encoding as it's not relevant to other browsers.Andrew White
-
Change translation key of
submit_tagfrommodule_name_class_nametomodule_name/class_name.Rui Onodera
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
Action Pack
-
Remove deprecated
fragment_cache_keyhelper in favor ofcombined_fragment_cache_key.Rafael Mendonça França
-
Remove deprecated methods in
ActionDispatch::TestResponse.#success?,missing?anderror?were deprecated in Rails 5.2 in favor of
#successful?,not_found?andserver_error?.Rafael Mendonça França
-
Ensure external redirects are explicitly allowed
Add
fallback_locationandallow_other_hostoptions toredirect_to.Gannon McGibbon
-
Introduce ActionDispatch::HostAuthorization
This is a new middleware that guards against DNS rebinding attacks by
white-listing the allowed hosts a request can be made to.Each host is checked with the case operator (
#===) to supportRegExp,
Proc,IPAddrand custom objects as host allowances.Genadi Samokovarov
-
Allow using
parsed_bodyinActionController::TestCase.In addition to
ActionDispatch::IntegrationTest, allow using
parsed_bodyinActionController::TestCase:class SomeControllerTest < ActionController::TestCase def test_some_action post :action, body: { foo: 'bar' } assert_equal({ "foo" => "bar" }, response.parsed_body) end endFixes #34676.
Tobias Bühlmann
-
Raise an error on root route naming conflicts.
Raises an ArgumentError when multiple root routes are defined in the
same context instead of assigning nil names to subsequent roots.Gannon McGibbon
-
Allow rescue from parameter parse errors:
rescue_from ActionDispatch::Http::Parameters::ParseError do head :unauthorized endGannon McGibbon, Josh Cheek
-
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
-
Add
ActionController::Parameters#each_value.Lukáš Zapletal
-
Deprecate
ActionDispatch::Http::ParameterFilterin favor ofActiveSupport::ParameterFilter.Yoshiyuki Kinjo
-
Encode Content-Disposition filenames on
send_dataandsend_file.
Previously,send_data 'data', filename: "\u{3042}.txt"sends
"filename=\"\u{3042}.txt\""as Content-Disposition and it can be
garbled.
Now it follows RFC 2231 and
RFC 5987 and sends
"filename=\"%3F.txt\"; filename*=UTF-8''%E3%81%82.txt".
Most browsers can find filename correctly and old browsers fallback to ASCII
converted name.Fumiaki Matsushima
-
Expose
ActionController::Parameters#each_keywhich allows iterating over
keys without allocating an array.Richard Schneeman
-
Purpose metadata for signed/encrypted cookies.
Rails can now thwart attacks that attempt to copy signed/encrypted value
of a cookie and use it as the value of another cookie.It does so by stashing the cookie-name in the purpose field which is
then signed/encrypted along with the cookie value. Then, on a server-side
read, we verify the cookie-names and discard any attacked cookies.Enable
action_dispatch.use_cookies_with_metadatato use this feature, which
writes cookies with the new purpose and expiry metadata embedded.Assain Jaleel
-
Raises
ActionController::RespondToMismatchErrorwith conflicitingrespond_toinvocations.respond_tocan match multiple types and lead to undefined behavior when
multiple invocations are made and the types do not match:respond_to do |outer_type| outer_type.js do respond_to do |inner_type| inner_type.html { render body: "HTML" } end end endPatrick Toomey
-
ActionDispatch::Http::UploadedFilenow delegatesto_pathto its tempfile.This allows uploaded file objects to be passed directly to
File.read
without raising aTypeError:uploaded_file = ActionDispatch::Http::UploadedFile.new(tempfile: tmp_file) File.read(uploaded_file)Aaron Kromer
-
Pass along arguments to underlying
getmethod infollow_redirect!.Now all arguments passed to
follow_redirect!are passed to the underlying
getmethod. This for example allows to set custom headers for the
redirection request to the server.follow_redirect!(params: { foo: :bar })Remo Fritzsche
-
Introduce a new error page to when the implicit render page is accessed in the browser.
Now instead of showing an error page that with exception and backtraces we now show only
one informative page.Vinicius Stock
-
Introduce
ActionDispatch::DebugExceptions.register_interceptor.Exception aware plugin authors can use the newly introduced
.register_interceptormethod to get the processed exception, instead of
monkey patching DebugExceptions.ActionDispatch::DebugExceptions.register_interceptor do |request, exception| HypoteticalPlugin.capture_exception(request, exception) endGenadi Samokovarov
-
Output only one Content-Security-Policy nonce header value per request.
Fixes #32597.
Andrey Novikov, Andrew White
-
Move default headers configuration into their own module that can be included in controllers.
Kevin Deisz
-
Add method
digtosession.claudiob, Takumi Shotoku
-
Controller level
force_sslhas been deprecated in favor of
config.force_ssl.Derek Prior
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
Active Job
-
Return false instead of the job instance when
enqueueis aborted.This will be the behavior in Rails 6.1 but it can be controlled now with
config.active_job.return_false_on_aborted_enqueue.Kir Shatrov
-
Keep executions for each specific declaration
Each
retry_ondeclaration has now its own specific executions counter. Before it was
shared between all executions of a job.Alberto Almagro
-
Allow all assertion helpers that have a
onlyandexceptkeyword to accept
Procs.Edouard Chin
-
Restore HashWithIndifferentAccess support to ActiveJob::Arguments.deserialize.
Gannon McGibbon
-
Include deserialized arguments in job instances returned from
assert_enqueued_withandassert_performed_withAlan Wu
-
Allow
assert_enqueued_with/assert_performed_withmethods to accept
a proc for theargsargument. This is useful to check if only a subset of arguments
matches your expectations.Edouard Chin
-
ActionDispatch::IntegrationTestincludesActiveJob::TestHelpermodule by default.Ricardo Díaz
-
Added
enqueue_retry.active_job,retry_stopped.active_job, anddiscard.active_jobhooks.steves
-
Allow
assert_performed_withto be called without a block.bogdanvlviv
-
Execution of
assert_performed_jobs, andassert_no_performed_jobs
without a block should respect passed:except,:only, and:queueoptions.bogdanvlviv
-
Allow
:queueoption to job assertions and helpers.bogdanvlviv
-
Allow
perform_enqueued_jobsto be called without a block.Performs all of the jobs that have been enqueued up to this point in the test.
Kevin Deisz
-
Move
enqueue/enqueue_atnotifications to an around callback.Improves timing accuracy over the old after callback by including
time spent writing to the adapter's IO implementation.Zach Kemp
-
Allow call
assert_enqueued_withwith no block.Example:
def test_assert_enqueued_with MyJob.perform_later(1,2,3) assert_enqueued_with(job: MyJob, args: [1,2,3], queue: 'low') MyJob.set(wait_until: Date.tomorrow.noon).perform_later assert_enqueued_with(job: MyJob, at: Date.tomorrow.noon) endbogdanvlviv
-
Allow passing multiple exceptions to
retry_on, anddiscard_on.George Claghorn
-
Pass the error instance as the second parameter of block executed by
discard_on.Fixes #32853.
Yuji Yaginuma
-
Remove support for Qu gem.
Reasons are that the Qu gem wasn't compatible since Rails 5.1,
gem development was stopped in 2014 and maintainers have
confirmed its demise. See issue #32273Alberto Almagro
-
Add support for timezones to Active Job.
Record what was the current timezone in effect when the job was
enqueued and then restore when the job is executed in same way
that the current locale is recorded and restored.Andrew White
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
-
Add support to define custom argument serializers.
Evgenii Pecherkin, Rafael Mendonça França
Action Mailer
-
Deprecate
ActionMailer::Base.receivein favor of Action Mailbox.George Claghorn
-
Add
MailDeliveryJobfor delivering both regular and parameterized mail. Deprecate usingDeliveryJobandParameterized::DeliveryJob.Gannon McGibbon
-
Fix ActionMailer assertions not working when a Mail defines
a custom delivery job classEdouard Chin
-
Mails with multipart
formatblocks with implicit render now also check for
a template name in options hash instead of only using the action name.Marcus Ilgner
-
ActionDispatch::IntegrationTestincludesActionMailer::TestHelpermodule by default.Ricardo Díaz
-
Add
perform_deliveriesto a payload ofdeliver.action_mailernotification.Yoshiyuki Kinjo
-
Change delivery logging message when
perform_deliveriesis false.Yoshiyuki Kinjo
-
Allow call
assert_enqueued_email_withwith no block.Example:
def test_email ContactMailer.welcome.deliver_later assert_enqueued_email_with ContactMailer, :welcome end def test_email_with_arguments ContactMailer.welcome("Hello", "Goodbye").deliver_later assert_enqueued_email_with ContactMailer, :welcome, args: ["Hello", "Goodbye"] endbogdanvlviv
-
Ensure mail gem is eager autoloaded when eager load is true to prevent thread deadlocks.
Samuel Cochran
-
Perform email jobs in
assert_emails.Gannon McGibbon
-
Add
Base.unregister_observer,Base.unregister_observers,
Base.unregister_interceptor,Base.unregister_interceptors,
Base.unregister_preview_interceptorandBase.unregister_preview_interceptors.
This makes it possible to dynamically add and remove email observers and
interceptors at runtime in the same way they're registered.Claudio Ortolina, Kota Miyake
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
Action Cable
-
Merge
action-cable-testingto Rails.Vladimir Dementyev
-
The JavaScript WebSocket client will no longer try to reconnect
when you callreject_unauthorized_connectionon the connection.Mick Staugaard
-
ActionCable.Connection#getStatenow references the configurable
ActionCable.adapters.WebSocketproperty rather than theWebSocketglobal
variable, matching the behavior ofActionCable.Connection#open.Richard Macklin
-
The ActionCable javascript package has been converted from CoffeeScript
to ES2015, and we now publish the source code in the npm distribution.This allows ActionCable users to depend on the javascript source code
rather than the compiled code, which can produce smaller javascript bundles.This change includes some breaking changes to optional parts of the
ActionCable javascript API:-
Configuration of the WebSocket adapter and logger adapter have been moved
from properties ofActionCableto properties ofActionCable.adapters.
If you are currently configuring these adapters you will need to make
these changes when upgrading:- ActionCable.WebSocket = MyWebSocket + ActionCable.adapters.WebSocket = MyWebSocket- ActionCable.logger = myLogger + ActionCable.adapters.logger = myLogger -
The
ActionCable.startDebugging()andActionCable.stopDebugging()
methods have been removed and replaced with the property
ActionCable.logger.enabled. If you are currently using these methods you
will need to make these changes when upgrading:- ActionCable.startDebugging() + ActionCable.logger.enabled = true- ActionCable.stopDebugging() + ActionCable.logger.enabled = false
Richard Macklin
-
-
Add
idoption to redis adapter so now you can distinguish
ActionCable's redis connections among others. Also, you can set
custom id in options.Before:
$ redis-cli client list id=669 addr=127.0.0.1:46442 fd=8 name= age=18 ...After:
$ redis-cli client list id=673 addr=127.0.0.1:46516 fd=8 name=ActionCable-PID-19413 age=2 ...Ilia Kasianenko
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
Active Storage
-
Replace
config.active_storage.queuewith two options that indicate which
queues analysis and purge jobs should use, respectively:config.active_storage.queues.analysisconfig.active_storage.queues.purge
config.active_storage.queueis preferred over the new options when it's
set, but it is deprecated and will be removed in Rails 6.1.George Claghorn
-
Permit generating variants of TIFF images.
Luciano Sousa
-
Use base36 (all lowercase) for all new Blob keys to prevent
collisions and undefined behavior with case-insensitive filesystems and
database indices.Julik Tarkhanov
-
It doesn’t include an
X-CSRF-Tokenheader if a meta tag is not found on
the page. It previously included one with a value ofundefined.Cameron Bothner
-
Fix
ArgumentErrorwhen uploading to amazon s3Hiroki Sanpei
-
Add progressive JPG to default list of variable content types
Maurice Kühlborn
-
Add
ActiveStorage.routes_prefixfor configuring generated routes.Chris Bisnett
-
ActiveStorage::Service::AzureStorageServiceonly handles specifically
relevant types ofAzure::Core::Http::HTTPError. It previously obscured
other types ofHTTPError, which is the azure-storage gem’s catch-all
exception class.Cameron Bothner
-
ActiveStorage::DiskController#showgenerates a 404 Not Found response when
the requested file is missing from the disk service. It previously raised
Errno::ENOENT.Cameron Bothner
-
ActiveStorage::Blob#downloadandActiveStorage::Blob#openraise
ActiveStorage::FileNotFoundErrorwhen the corresponding file is missing
from the storage service. Services translate service-specific missing object
exceptions (e.g.Google::Cloud::NotFoundErrorfor the GCS service and
Errno::ENOENTfor the disk service) into
ActiveStorage::FileNotFoundError.Cameron Bothner
-
Added the
ActiveStorage::SetCurrentconcern for custom Active Storage
controllers that can't inherit fromActiveStorage::BaseController.George Claghorn
-
Active Storage error classes like
ActiveStorage::IntegrityErrorand
ActiveStorage::UnrepresentableErrornow inherit fromActiveStorage::Error
instead ofStandardError. This permits rescuingActiveStorage::Errorto
handle all Active Storage errors.Andrei Makarov, George Claghorn
-
Uploaded files assigned to a record are persisted to storage when the record
is saved instead of immediately.In Rails 5.2, the following causes an uploaded file in
params[:avatar]to
be stored:@user.avatar = params[:avatar]In Rails 6, the uploaded file is stored when
@useris successfully saved.George Claghorn
-
Add the ability to reflect on defined attachments using the existing
ActiveRecord reflection mechanism.Kevin Deisz
-
Variant arguments of
falseornilwill no longer be passed to the
processor. For example, the following will not have the monochrome
variation applied:avatar.variant(monochrome: false)Jacob Smith
-
Generated attachment getter and setter methods are created
within the model'sGeneratedAssociationMethodsmodule to
allow overriding and composition usingsuper.Josh Susser, Jamon Douglas
-
Add
ActiveStorage::Blob#open, which downloads a blob to a tempfile on disk
and yields the tempfile. DeprecateActiveStorage::Downloading.David Robertson, George Claghorn
-
Pass in
identify: falseas an argument when providing acontent_typefor
ActiveStorage::Attached::{One,Many}#attachto bypass automatic content
type inference. For example:@message.image.attach( io: File.open('/path/to/file'), filename: 'file.pdf', content_type: 'application/pdf', identify: false )Ryan Davidson
-
The Google Cloud Storage service properly supports streaming downloads.
It now requires version 1.11 or newer of the google-cloud-storage gem.George Claghorn
-
Use the ImageProcessing gem
for Active Storage variants, and deprecate the MiniMagick backend.This means that variants are now automatically oriented if the original
image was rotated. Also, in addition to the existing ImageMagick
operations, variants can now use:resize_to_fit,:resize_to_fill, and
other ImageProcessing macros. These are now recommended over raw:resize,
as they also sharpen the thumbnail after resizing.The ImageProcessing gem also comes with a backend implemented on
libvips, an alternative to
ImageMagick which has significantly better performance than
ImageMagick in most cases, both in terms of speed and memory usage. In
Active Storage it's now possible to switch to the libvips backend by
changingRails.application.config.active_storage.variant_processorto
:vips.Janko Marohnić
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
Action Mailbox
-
Added to Rails.
DHH
Action Text
-
Added to Rails.
DHH
Railties
-
Remove deprecated
after_bundlehelper inside plugins templates.Rafael Mendonça França
-
Remove deprecated support to old
config.ruthat use the application class as argument ofrun.Rafael Mendonça França
-
Remove deprecated
environmentargument from the rails commands.Rafael Mendonça França
-
Remove deprecated
capify!.Rafael Mendonça França
-
Remove deprecated
config.secret_token.Rafael Mendonça França
-
Seed database with inline ActiveJob job adapter.
Gannon McGibbon
-
Add
rails db:system:changecommand for changing databases.bin/rails db:system:change --to=postgresql force config/database.yml gsub GemfileThe change command copies a template
config/database.ymlwith the target database adapter into your app, and replaces your database gem with the target database gem.Gannon McGibbon
-
Add
rails test:channels.bogdanvlviv
-
Use original
bundlerenvironment variables during the process of generating a new rails project.Marco Costa
-
Send Active Storage analysis and purge jobs to dedicated queues by default.
Analysis jobs now use the
:active_storage_analysisqueue, and purge jobs
now use the:active_storage_purgequeue. This matches Action Mailbox,
which sends its jobs to dedicated queues by default.George Claghorn
-
Add
rails test:mailboxes.George Claghorn
-
Introduce guard against DNS rebinding attacks
The
ActionDispatch::HostAuthorizationis a new middleware that prevent
against DNS rebinding and otherHostheader attacks. It is included in
the development environment by default with the following configuration:Rails.application.config.hosts = [ IPAddr.new("0.0.0.0/0"), # All IPv4 addresses. IPAddr.new("::/0"), # All IPv6 addresses. "localhost" # The localhost reserved domain. ]In other environments
Rails.application.config.hostsis empty and no
Hostheader checks will be done. If you want to guard against header
attacks on production, you have to manually whitelist the allowed hosts
with:Rails.application.config.hosts << "product.com"The host of a request is checked against the
hostsentries with the case
operator (#===), which letshostssupport entries of typeRegExp,
ProcandIPAddrto name a few. Here is an example with a regexp.# Allow requests from subdomains like `www.product.com` and # `beta1.product.com`. Rails.application.config.hosts << /.*\.product\.com/A special case is supported that allows you to whitelist all sub-domains:
# Allow requests from subdomains like `www.product.com` and # `beta1.product.com`. Rails.application.config.hosts << ".product.com"Genadi Samokovarov
-
Remove redundant suffixes on generated helpers.
Gannon McGibbon
-
Remove redundant suffixes on generated integration tests.
Gannon McGibbon
-
Fix boolean interaction in scaffold system tests.
Gannon McGibbon
-
Remove redundant suffixes on generated system tests.
Gannon McGibbon
-
Add an
abort_on_failureboolean option to the generator method that shell
out (generate,rake,rails_command) to abort the generator if the
command fails.David Rodríguez
-
Remove
app/assetsandapp/javascriptfromeager_load_pathsandautoload_paths.Gannon McGibbon
-
Use Ids instead of memory addresses when displaying references in scaffold views.
Fixes #29200.
Rasesh Patel
-
Adds support for multiple databases to
rails db:migrate:status.
Subtasks are also added to get the status of individual databases (eg.rails db:migrate:status:animals).Gannon McGibbon
-
Use Webpacker by default to manage app-level JavaScript through the new app/javascript directory.
Sprockets is now solely in charge, by default, of compiling CSS and other static assets.
Action Cable channel generators will create ES6 stubs rather than use CoffeeScript.
Active Storage, Action Cable, Turbolinks, and Rails-UJS are loaded by a new application.js pack.
Generators no longer generate JavaScript stubs.DHH, Lachlan Sylvester
-
Add
database(aliased asdb) option to model generator to allow
setting the database. This is useful for applications that use
multiple databases and put migrations per database in their own directories.bin/rails g model Room capacity:integer --database=kingston invoke active_record create db/kingston_migrate/20180830151055_create_rooms.rbBecause rails scaffolding uses the model generator, you can
also specify a database with the scaffold generator.Gannon McGibbon
-
Raise an error when "recyclable cache keys" are being used by a cache store
that does not explicitly support it. Custom cache keys that do support this feature
can bypass this error by implementing thesupports_cache_versioning?method on their
class and returning a truthy value.Richard Schneeman
-
Support environment specific credentials overrides.
So any environment will look for
config/credentials/#{Rails.env}.yml.encand fall back
toconfig/credentials.yml.enc.The encryption key can be in
ENV["RAILS_MASTER_KEY"]orconfig/credentials/production.key.Environment credentials overrides can be edited with
rails credentials:edit --environment production.
If no override is setup for the passed environment, it will be created.Additionally, the default lookup paths can be overwritten with these configs:
config.credentials.content_pathconfig.credentials.key_path
Wojciech Wnętrzak
-
Make
ActiveSupport::Cache::NullStorethe default cache store in the test environment.Michael C. Nelson
-
Emit warning for unknown inflection rule when generating model.
Yoshiyuki Kinjo
-
Add
database(aliased asdb) option to migration generator.If you're using multiple databases and have a folder for each database
for migrations (ex db/migrate and db/new_db_migrate) you can now pass the
--databaseoption to the generator to make sure the the migration
is inserted into the correct folder.rails g migration CreateHouses --database=kingston invoke active_record create db/kingston_migrate/20180830151055_create_houses.rbEileen M. Uchitelle
-
Deprecate
rake routesin favor ofrails routes.Yuji Yaginuma
-
Deprecate
rake initializersin favor ofrails initializers.Annie-Claude Côté
-
Deprecate
rake dev:cachein favor ofrails dev:cache.Annie-Claude Côté
-
Deprecate
rails notessubcommands in favor of passing anannotationsargument torails notes.The following subcommands are replaced by passing
--annotationsor-atorails notes:rails notes:custom ANNOTATION=customis deprecated in favor of usingrails notes -a custom.rails notes:optimizeis deprecated in favor of usingrails notes -a OPTIMIZE.rails notes:todois deprecated in favor of usingrails notes -a TODO.rails notes:fixmeis deprecated in favor of usingrails notes -a FIXME.
Annie-Claude Côté
-
Deprecate
SOURCE_ANNOTATION_DIRECTORIESenvironment variable used byrails notes
throughRails::SourceAnnotationExtractor::Annotationin favor of usingconfig.annotations.register_directories.Annie-Claude Côté
-
Deprecate
rake notesin favor ofrails notes.Annie-Claude Côté
-
Don't generate unused files in
app:updatetask.Skip the assets' initializer when sprockets isn't loaded.
Skip
config/spring.rbwhen spring isn't loaded.Skip yarn's contents when yarn integration isn't used.
Tsukuru Tanimichi
-
Make the master.key file read-only for the owner upon generation on
POSIX-compliant systems.Previously:
$ ls -l config/master.key -rw-r--r-- 1 owner group 32 Jan 1 00:00 master.keyNow:
$ ls -l config/master.key -rw------- 1 owner group 32 Jan 1 00:00 master.keyFixes #32604.
Jose Luis Duran
-
Deprecate support for using the
HOSTenvironment to specify the server IP.The
BINDINGenvironment should be used instead.Fixes #29516.
Yuji Yaginuma
-
Deprecate passing Rack server name as a regular argument to
rails server.Previously:
$ bin/rails server thinThere wasn't an explicit option for the Rack server to use, now we have the
--usingoption with the-ushort switch.Now:
$ bin/rails server -u thinThis change also improves the error message if a missing or mistyped rack
server is given.Genadi Samokovarov
-
Add "rails routes --expanded" option to output routes in expanded mode like
"psql --expanded". Result looks like:$ rails routes --expanded --[ Route 1 ]------------------------------------------------------------ Prefix | high_scores Verb | GET URI | /high_scores(.:format) Controller#Action | high_scores#index --[ Route 2 ]------------------------------------------------------------ Prefix | new_high_score Verb | GET URI | /high_scores/new(.:format) Controller#Action | high_scores#newBenoit Tigeot
-
Rails 6 requires Ruby 2.5.0 or newer.
Jeremy Daer, Kasper Timm Hansen
- Ruby
Published by rafaelfranca over 7 years ago
https://github.com/rails/rails - 5.2.2
Active Support
-
Fix bug where
#to_optionsforActiveSupport::HashWithIndifferentAccess
would not act as alias for#symbolize_keys.Nick Weiland
-
Improve the logic that detects non-autoloaded constants.
Jan Habermann, Xavier Noria
-
Fix bug where
URI.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::MissingAttributeError
if the attribute does not exist.Sean Griffin
-
Do not use prepared statement in queries that have a large number of binds.
Ryuta Kamizono
-
Fix query cache to load before first request.
Eileen M. Uchitelle
-
Fix collection cache key with limit and custom select to avoid ambiguous timestamp column error.
Fixes #33056.
Federico Martinez
-
Fix duplicated record creation when using nested attributes with
create_with.Darwin Wu
-
Fix regression setting children record in parent
before_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
- Ruby
Published by rafaelfranca over 7 years ago