-
Correctly pass MySQL options when using structure_dump or structure_load
Specifically, it fixes an issue when using SSL authentication.
Alex Coomans
-
Fixes custom primary keys for associations when calling
Relation#whereFixes #23327.
Rick Song
-
No longer pass deprecated option
-itopg_dump.Paul Sadauskas
- No changes.
- No changes.
-
No longer pass deprecated option
-itopg_dump.Paul Sadauskas
-
Includes HABTM returns correct size now. It's caused by the join dependency only instantiates one HABTM object because the join table hasn't a primary key.
Fixes #16032.
Examples:
before: Project.first.salaried_developers.size # => 3 Project.includes(:salaried_developers).first.salaried_developers.size # => 1 after: Project.first.salaried_developers.size # => 3 Project.includes(:salaried_developers).first.salaried_developers.size # => 3Bigxiang
-
Don't define autosave association callbacks twice from
accepts_nested_attributes_for.Fixes #18704.
Sean Griffin
-
Raises the right exception when declares a has many through association with missing source.
Mauro George
-
Revert behavior of
db:schema:loadback to loading the full environment. This ensures that initializers are run.Fixes #19545.
Yves Senn
-
Rename
:classto:anonymous_classin association options.Fixes #19659.
Andrew White
-
Fix referencing wrong table aliases while joining tables of has many through association (only when calling calculation methods).
Fixes #19276.
pinglamb
- No changes.
-
Fixed ActiveRecord::Relation#becomes! and changed_attributes issues for type column
Fixes #17139.
Miklos Fazekas
-
A
NullRelationshould represent nothing. This fixes a bug whereComment.where(post_id: Post.none)returned a non-empty result.Closes #15176.
Matthew Draper, Yves Senn
-
Respect custom primary keys for associations when calling
Relation#whereFixes #18813.
Sean Griffin
-
Fixed ActiveRecord::Relation#group method when argument is SQL reserved key word:
SplitTest.group(:key).count Property.group(:value).count
Bogdan Gusiev
-
Fixed setting of foreign_key for through associations while building of new record.
Fixes #12698.
Ivan Antropov
-
Fixed automatic inverse_of for models nested in module.
Andrew McCloud
-
Fix
reaping_frequencyoption when the value is a string.This usually happens when it is configured using
DATABASE_URL.korbin
-
db:schema:loadanddb:structure:loadno longer purge the database before loading the schema. This is left for the user to do.db:test:preparewill still purge the database.Closes #17945.
Yves Senn
-
Bring back
db:test:prepareto synchronize the test database schema.Manual synchronization using
bin/rake db:test:prepareis required when a migration is rolled-back, edited and reapplied.ActiveRecord::Base.maintain_test_schemanow usesdb:test:prepareto synchronize the schema. Plugins can use this task as a hook to provide custom behavior after the schema has been loaded.NOTE:
test:prepareruns before the schema was synchronized.Fixes #17171, #15787.
Yves Senn
-
Renaming a table in pg also renames the primary key index.
Fixes #12856
Sean Griffin
-
Make it possible to access fixtures excluded by a
default_scope.Yves Senn
-
timestampsandadd_timestampspasses additional options along. (likenull: false)Closes #17624.
Yves Senn
-
Cache
CollectionAssociation#readerproxies separately before and after the owner has been saved so that the proxy is not cached without the owner's id.Ben Woosley
-
Fix preloading of associations which unscope a default scope.
Fixes #11036.
Byron Bischoff
-
Do not use
RENAME INDEXsyntax for MariaDB 10.0.Fixes #15931.
Jeff Browning
-
Allow included modules to override association methods.
Fixes #16684.
Yves Senn
-
Schema loading rake tasks (like
db:schema:loadanddb:setup) maintain the database connection to the current environment.Fixes #16757.
Joshua Cody, Yves Senn
-
db:purgewith MySQL respectsRails.env.Yves Senn
-
Fixed automatic maintaining test schema to properly handle sql structure schema format.
Fixes #15394.
Wojciech Wnętrzak
-
Fix has_many :through relation merging failing when dynamic conditions are passed as a lambda with an arity of one.
Fixes #16128.
Agis Anastasopoulos
- No changes.
- No changes.
-
Fixed a regression where whitespaces were stripped from DISTINCT queries in PostgreSQL.
Agis Anastasopoulos
Fixes #16623.
-
Fixed an issue where custom accessor methods (such as those generated by
enum) with the same name as a global method are incorrectly overridden when subclassing.Fixes #16288.
-
Baseclass becomes! subclass.
Before this change, a record which changed its STI type, could not be found when updated. Setting update_record to the base class, ensures the record can be found.
Fixes #14785.
Matthew Draper, Earl St Sauver, Edo Balvers
-
Fix regression on after_commit that didnt fire when having nested transactions.
Fixes #16425.
arthurnn
-
Define
id_wasto get the previous value of the primary key.Currently when we call id_was and we have a custom primary key name Active Record will return the current value of the primary key. This make impossible to correctly do an update operation if you change the id.
Fixes #16413.
Rafael Mendonça França
-
Fix the schema dump generated for tables without constraints and with primary key with default value of custom PostgreSQL function result.
Fixes #16111.
Andrey Novikov
-
Restore 4.0 behavior for using serialize attributes with
JSONas coder.With 4.1.x,
serializestarted returning a string whenJSONwas passed as the second attribute. It will now return a hash as per previous versions.Example:
class Post < ActiveRecord::Base serialize :comment, JSON end class Comment include ActiveModel::Model attr_accessor :category, :text end post = Post.create! post.comment = Comment.new(category: "Animals", text: "This is a comment about squirrels.") post.save! # 4.0 post.comment # => {"category"=>"Animals", "text"=>"This is a comment about squirrels."} # 4.1 before post.comment # => "#<Comment:0x007f80ab48ff98>" # 4.1 after post.comment # => {"category"=>"Animals", "text"=>"This is a comment about squirrels."}When using
JSONas the coder inserialize, Active Record will use the newActiveRecord::Coders::JSONcoder which delegates itsdump/loadtoActiveSupport::JSON.encode/decode. This ensures special objects are dumped correctly using the#as_jsonhook.To keep the previous behaviour, supply a custom coder instead (example).
Fixes #15594.
Jenn Cooper
-
Fixed error in
reset_counterswhen associations haveselectscope. (Call tocountgenerates invalid SQL.)Cade Truitt
-
After a successful
reload,new_record?is always false.Fixes #12101.
Matthew Draper
-
Correctly extract IPv6 addresses from
DATABASE_URI: the square brackets are part of the URI structure, not the actual host.Fixes #15705.
Andy Bakun, Aaron Stone
-
Don't error when quoting user defined types in PostgreSQL.
Fixes #15697.
Sean Griffin
-
Ensure both parent IDs are set on join records when both sides of a through association are new.
Sean Griffin
-
Pluck now works when selecting columns from different tables with the same name.
Fixes #15649.
Sean Griffin
-
ActiveRecord::FinderMethods.findwith block can handle proc parameter asEnumerable#finddoes.Fixes #15382.
James Yang
-
ActiveRecord::SchemaMigrationhas no primary key regardless of theprimary_key_prefix_typeconfiguration.Fixes #15051.
JoseLuis Torres, Yves Senn
-
rake db:migrate:statusworks with legacy migration numbers like00018_xyz.rb.Fixes #15538.
Yves Senn
-
Fixed
columns_for_distinctof postgresql adapter to work correctly with orders without sort direction modifiers.Nikolay Kondratyev
-
Keep PostgreSQL
hstoreandjsonattributes asHashin@attributes. Fixes duplication in combination withstore_accessor.Fixes #15369.
Yves Senn
-
rake railties:install:migrationsrespects the order of railties.Arun Agrawal
- No changes.
-
Fix regression added from the latest security fix.
Sean Griffin, Matthew Draper
-
Fix SQL Injection Vulnerability in 'range' quoting.
Fixes CVE-2014-3483
Rafael Mendonça França
-
Fix regression on eager loading association based on SQL query rather than existing column.
Fixes #15480.
Lauro Caetano, Carlos Antonio da Silva
-
Fix redefine a has_and_belongs_to_many inside inherited class Fixing regression case, where redefining the same has_an_belongs_to_many definition into a subclass would raise.
Fixes #14983.
arthurnn
-
Fix has_and_belongs_to_many public reflection. When defining a has_and_belongs_to_many, internally we convert that to two has_many. But as
reflectionsis a public API, people expect to see the right macro.Fixes #14682.
arthurnn
-
Fixed serialization for records with an attribute named
format.Fixes #15188.
Godfrey Chan
-
Fixed serialized fields returning serialized data after being updated with
update_column.Simon Hørup Eskildsen
-
When a
groupis set,sum,size,average,minimumandmaximumon a NullRelation should return a Hash.Kuldeep Aggarwal
-
Fixed polymorphic eager loading when using a String as foreign key.
Fixes #14734.
Lauro Caetano
-
Fixed the inferred table name of a has_and_belongs_to_many auxiliar table inside a schema.
Fixes #14824
Eric Chahin
-
Fix bug that added
table_name_prefixandtable_name_suffixto extension names in PostgreSQL when migrating.Joao Carlos
-
Floats with limit >= 25 that get turned into doubles in MySQL no longer have their limit dropped from the schema.
Fixes #14135.
Aaron Nelson
-
Fix how to calculate associated class name when using namespaced has_and_belongs_to_many association.
Fixes #14709.
Kassio Borges
-
ActiveRecord::Relation::Merger#filter_bindsnow compares equivalent symbols and strings in column names as equal.This fixes a rare case in which more bind values are passed than there are placeholders for them in the generated SQL statement, which can make PostgreSQL throw a
StatementInvalidexception.Nat Budin
-
Fix
stored_attributesto correctly merge the details of stored attributes defined in parent classes.Fixes #14672.
Brad Bennett, Jessica Yao, Lakshmi Parthasarathy
-
change_column_defaultallows[]as argument tochange_column_default.Fixes #11586.
Yves Senn
-
Fix
PostgreSQLAdapter::OID::Float#type_castto convert Infinity and NaN PostgreSQL values into a native RubyFloat::INFINITYandFloat::NANExample:
# Before Point.create(value: 1.0/0) Point.last.value # => 0.0 # After Point.create(value: 1.0/0) Point.last.value # => InfinityInnokenty Mikhailov
-
Allow the PostgreSQL adapter to handle bigserial primary key types again.
Fixes #10410.
Patrick Robertson
-
Fixed has_and_belongs_to_many's CollectionAssociation size calculation.
has_and_belongs_to_many should fall back to using the normal CollectionAssociation's size calculation if the collection is not cached or loaded.
Fixes #14913 and #14914.
Fred Wu
-
Revert the behaviour of
ActiveRecord::Relation#joinchanged through 4.0 => 4.1 to 4.0.In 4.1.0
Relation#joinis delegated toArel#SelectManager. In 4.0 series it is delegated toArray#join.Bogdan Gusiev
-
Log nil binary column values correctly.
When an object with a binary column is updated with a nil value in that column, the SQL logger would throw an exception when trying to log that nil value. This only occurs when updating a record that already has a non-nil value in that column since an initial nil value isn't included in the SQL anyway (at least, when dirty checking is enabled.) The column's new value will now be logged as
<NULL binary data>to parallel the existing<N bytes of binary data>for non-nil values.James Coleman
-
Stringify all variables keys of MySQL connection configuration.
When
sql_modevariable for MySQL adapters set in configuration asStringwas ignored and overwritten by strict mode option.Fixes #14895.
Paul Nikitochkin
-
Ensure SQLite3 statements are closed on errors.
Fixes #13631.
Timur Alperovich
-
Fix excluding lower bounds of PostgreSQL date and int ranges.
River MacLeod, Yves Senn
-
When using a custom
join_tablename on ahabtm, rails was not saving it on Reflections. This causes a problem when rails loads fixtures, because it uses the reflections to set database with fixtures.Fixes #14845.
Kassio Borges
-
ActiveRecord::Base.no_touchingno longer triggers callbacks or start empty transactions.Fixes #14841.
Lucas Mazza
-
Fix name collision with
Array#select!withRelation#select!.Fixes #14752.
Earl St Sauver
-
Fixed unexpected behavior for
has_many :throughassociations going through a scopedhas_many.If a
has_manyassociation is adjusted using a scope, and anotherhas_many :throughuses this association, then the scope adjustment is unexpectedly neglected.Fixes #14537.
Jan Habermann
-
When a destroyed record is duped, the dup is not
destroyed?.Kuldeep Aggarwal
-
Fixed has_many association to make it support irregular inflections.
Fixes #8928.
arthurnn, Javier Goizueta
-
Calling
delete_allon an unloadedCollectionProxyno longer generates a SQL statement containing each id of the collection:Before:
DELETE FROM `model` WHERE `model`.`parent_id` = 1 AND `model`.`id` IN (1, 2, 3...)After:
DELETE FROM `model` WHERE `model`.`parent_id` = 1Eileen M. Uchitelle, Aaron Patterson
-
Fixed a problem where count used with a grouping was not returning a Hash.
Fixes #14721.
Eric Chahin
-
Do not quote uuid default value on
change_column.Fixes #14604.
Eric Chahin
-
The comparison between
RelationandCollectionProxyshould be consistent.Example:
author.posts == Post.where(author_id: author.id) # => true Post.where(author_id: author.id) == author.posts # => trueFixes #13506.
Lauro Caetano
-
PostgreSQL adapter only warns once for every missing OID per connection.
Fixes #14275.
Matthew Draper, Yves Senn
-
Fixed error for aggregate methods (
empty?,any?,count) withselectwhich created invalid SQL.Fixes #13648.
Simon Woker
-
Fix insertion of records via
has_many :throughassociation with scope.Fixes #3548.
Ivan Antropov
-
Make possible to have an association called
records.Fixes #11645.
prathamesh-sonpatki
-
to_sqlon an association now matches the query that is actually executed, where it could previously have incorrectly accrued additional conditions (e.g. as a result of a previous query). CollectionProxy now always defers to the association scope'sarelmethod so the (incorrect) inherited one should be entirely concealed.Fixes #14003.
Jefferson Lai
-
Fixed error when using
with_optionswith lambda.Fixes #9805.
Lauro Caetano
-
Fixed error when specifying a non-empty default value on a PostgreSQL array column.
Fixes #10613.
Luke Steensen
-
Fixed error where .persisted? throws SystemStackError for an unsaved model with a custom primary key that didn't save due to validation error.
Fixes #14393.
Chris Finne
-
rake db:structure:dumponly dumps schema information if the schema migration table exists.Fixes #14217.
Yves Senn
-
Add support for
Relationbe passed as parameter onQueryCache#select_all.Fixes #14361.
arthurnn
-
Only save
has_oneassociations if record has changes. Previously after save related callbacks, such as#after_commit, were triggered when thehas_oneobject did not get saved to the db.Alan Kennedy
- No changes.
-
Fixed a problem where an enum would overwrite values of another enum with the same name in an unrelated class.
Fixes #14607.
Evan Whalen
-
Block a few default Class methods as scope name.
For instance, this will raise:
scope :public, -> { where(status: 1) }arthurnn
-
Deprecate SQLite database URLs containing an authority.
The current "correct" spellings for in-memory, relative, and absolute URLs, respectively, are:
sqlite3::memory: sqlite3:relative/path sqlite3:/full/pathThe previous spelling (
sqlite3:///relative/path) continues to work as it did in Rails 4.0, but with a deprecation warning: in the next release, that spelling will instead be interpreted as an absolute path.Matthew Draper
-
where.notaddsreferencesforincludeslike normalwherecalls do.Fixes #14406.
Yves Senn
-
includesis able to detect the right preloading strategy when string joins are involved.Fixes #14109.
Aaron Patterson, Yves Senn
-
Fixed error with validation with enum fields for records where the value for any enum attribute is always evaluated as 0 during uniqueness validation.
Fixes #14172.
Vilius Luneckas Ahmed AbouElhamayed
-
before_addcallbacks are fired before the record is saved onhas_and_belongs_to_manyassocations and onhas_many :throughassociations. Before this change,before_addcallbacks would be fired before the record was saved onhas_and_belongs_to_manyassociations, but not onhas_many :throughassociations.Fixes #14144.
-
Fixed STI classes not defining an attribute method if there is a conflicting private method defined on its ancestors.
Fixes #11569.
Godfrey Chan
-
Default scopes are no longer overriden by chained conditions.
Before this change when you defined a
default_scopein a model it was overriden by chained conditions in the same field. Now it is merged like any other scope.Before:
class User < ActiveRecord::Base default_scope { where state: 'pending' } scope :active, -> { where state: 'active' } scope :inactive, -> { where state: 'inactive' } end User.all # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' User.active # SELECT "users".* FROM "users" WHERE "users"."state" = 'active' User.where(state: 'inactive') # SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'After:
class User < ActiveRecord::Base default_scope { where state: 'pending' } scope :active, -> { where state: 'active' } scope :inactive, -> { where state: 'inactive' } end User.all # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' User.active # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'active' User.where(state: 'inactive') # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'inactive'To get the previous behavior it is needed to explicitly remove the
default_scopecondition usingunscoped,unscope,rewhereorexcept.Example:
class User < ActiveRecord::Base default_scope { where state: 'pending' } scope :active, -> { unscope(where: :state).where(state: 'active') } scope :inactive, -> { rewhere state: 'inactive' } end User.all # SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' User.active # SELECT "users".* FROM "users" WHERE "users"."state" = 'active' User.inactive # SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive' -
Perform necessary deeper encoding when hstore is inside an array.
Fixes #11135.
Josh Goodall, Genadi Samokovarov
-
Properly detect if a connection is still active before using it in multi-threaded environments.
Fixes #12867.
Kevin Casey, Matthew Draper, William (B.J.) Snow Orvis
-
When inverting add_index use the index name if present instead of the columns.
If there are two indices with matching columns and one of them is explicitly named then reverting the migration adding the named one would instead drop the unnamed one.
The inversion of add_index will now drop the index by its name if it is present.
Hubert Dąbrowski
-
Add flag to disable schema dump after migration.
Add a config parameter on Active Record named
dump_schema_after_migrationwhich is true by default. Now schema dump does not happen at the end of migration rake task ifdump_schema_after_migrationis false.Emil Soman
-
find_in_batches,find_each,Result#eachandEnumerable#index_bynow return anEnumeratorthat can calculate its size.See also #13938.
Marc-André Lafortune
-
Make sure transaction state gets reset after a commit operation on the record.
If a new transaction was open inside a callback, the record was loosing track of the transaction level state, and it was leaking that state.
Fixes #12566.
arthurnn
-
Pass
has_and_belongs_to_many:autosaveoption to the underlyinghas_many :throughassociation.Fixes #13923.
Yves Senn
-
PostgreSQL implementation of
SchemaStatements#index_name_exists?.The database agnostic implementation does not detect with indexes that are not supported by the ActiveRecord schema dumper. For example, expressions indexes would not be detected.
Fixes #11018.
Jonathan Baudanza
-
Parsing PostgreSQL arrays with empty strings now works correctly.
Previously, if you tried to parse
{"1","","2","","3"}the result would be["1","2","3"], removing the empty strings from the array, which would be incorrect. Now it will correctly produce["1","","2","","3"]as the result of parsing the above PostgreSQL array.Fixes #13907.
Maurício Linhares
-
Associations now raise
ArgumentErroron name conflicts.Dangerous association names conflicts include instance or class methods already defined by
ActiveRecord::Base.Example:
class Car < ActiveRecord::Base has_many :errors end # Will raise ArgumentError.Fixes #13217.
Lauro Caetano
-
Fix regressions on
select_*methods. Whenselect_*methods receive aRelationobject, they should be able to get the arel/binds from it. Also fix regressions onselect_rowsthat was ignoring the binds.Fixes #7538, #12017, #13731, #12056.
arthurnn
-
Active Record objects can now be correctly dumped, loaded and dumped again without issues.
Previously, if you did
YAML.dump,YAML.loadand thenYAML.dumpagain in an Active Record model that used serialization it would fail at the last dump due to the fields not being correctly serialized before being dumped to YAML. Now it is possible to dump and load the same object as many times as needed without any issues.Fixes #13861.
Maurício Linhares
-
find_in_batchesnow returns anEnumeratorwhen called without a block, so that it can be chained with otherEnumerablemethods.Marc-André Lafortune
-
enumnow raises on "dangerous" name conflicts.Dangerous name conflicts includes instance or class method conflicts with methods defined within
ActiveRecord::Basebut not its ancestors, as well as conflicts with methods generated by other enums on the same class.Fixes #13389.
Godfrey Chan
-
scopenow raises on "dangerous" name conflicts.Similar to dangerous attribute methods, a scope name conflict is dangerous if it conflicts with an existing class method defined within
ActiveRecord::Basebut not its ancestors.See also #13389.
Godfrey Chan, Philippe Creux
-
Correctly send an user provided statement to a
lock!()call.person.lock! 'FOR SHARE NOWAIT' # Before: SELECT * ... LIMIT 1 FOR UPDATE # After: SELECT * ... LIMIT 1 FOR SHARE NOWAITFixes #13788.
Maurício Linhares
-
Handle aliased attributes
select(),order()andreorder().Tsutomu Kuroda
-
Reset the collection association when calling
reseton it.Before:
post.comments.loaded? # => true post.comments.reset post.comments.loaded? # => trueAfter:
post.comments.loaded? # => true post.comments.reset post.comments.loaded? # => falseFixes #13777.
Kelsey Schlarman
-
Make enum fields work as expected with the
ActiveModel::DirtyAPI.Before this change, using the dirty API would have surprising results:
conversation = Conversation.new conversation.status = :active conversation.status = :archived conversation.status_was # => 0After this change, the same code would result in:
conversation = Conversation.new conversation.status = :active conversation.status = :archived conversation.status_was # => "active"Rafael Mendonça França
-
has_oneandbelongs_toaccessors don't add ORDER BY to the queries anymore.Since Rails 4.0, we add an ORDER BY in the
firstmethod to ensure consistent results among different database engines. But for singular associations this behavior is not needed since we will have one record to return. As this ORDER BY option can lead some performance issues we are removing it for singular associations accessors.Fixes #12623.
Rafael Mendonça França
-
Prepend table name for column names passed to
Relation#select.Example:
Post.select(:id) # Before: => SELECT id FROM "posts" # After: => SELECT "posts"."id" FROM "posts"Yves Senn
-
Fail early with "Primary key not included in the custom select clause" in
find_in_batches.Before this patch, the exception was raised after the first batch was yielded to the block. This means that you only get it, when you hit the
batch_sizetreshold. This could shadow the issue in development.Alexander Balashov
-
Ensure
secondthroughfifthmethods act like thefirstfinder.The famous ordinal Array instance methods defined in ActiveSupport (
first,second,third,fourth, andfifth) are now available as full-fledged finders in ActiveRecord. The biggest benefit of this is ordering of the records returned now defaults to the table's primary key in ascending order.Fixes #13743.
Example:
User.all.second # Before # => 'SELECT "users".* FROM "users"' # After # => SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 OFFSET 1' User.offset(3).second # Before # => 'SELECT "users".* FROM "users" LIMIT -1 OFFSET 3' # sqlite3 gem # => 'SELECT "users".* FROM "users" OFFSET 3' # pg gem # => 'SELECT `users`.* FROM `users` LIMIT 18446744073709551615 OFFSET 3' # mysql2 gem # After # => SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 OFFSET 4'Jason Meller
-
ActiveRecord states are now correctly restored after a rollback for models that did not define any transactional callbacks (i.e.
after_commit,after_rollbackorafter_create).Fixes #13744.
Godfrey Chan
-
Make
touchfire theafter_commitandafter_rollbackcallbacks.Harry Brundage
-
Enable partial indexes for
sqlite >= 3.8.0.See http://www.sqlite.org/partialindex.html
Cody Cutrer
-
Don't try to get the subclass if the inheritance column doesn't exist
The
subclass_from_attrsmethod is called even if the column specified by theinheritance_columnsetting doesn't exist. This prevents setting associations via the attributes hash if the association name clashes with the value of the setting, typically:type. This worked previously in Rails 3.2.Ujjwal Thaakar
-
Enum mappings are now exposed via class methods instead of constants.
Example:
class Conversation < ActiveRecord::Base enum status: [ :active, :archived ] endBefore:
Conversation::STATUS # => { "active" => 0, "archived" => 1 }After:
Conversation.statuses # => { "active" => 0, "archived" => 1 }Godfrey Chan
-
Set
NameError#namewhen STI-class-lookup fails.Chulki Lee
-
Fix bug in
becomes!when changing from the base model to a STI sub-class.Fixes #13272.
the-web-dev, Yves Senn
-
Currently Active Record can be configured via the environment variable
DATABASE_URLor by manually injecting a hash of values which is what Rails does, reading indatabase.ymland setting Active Record appropriately. Active Record expects to be able to useDATABASE_URLwithout the use of Rails, and we cannot rip out this functionality without deprecating. This presents a problem though when both config is set, and aDATABASE_URLis present. Currently theDATABASE_URLshould "win" and none of the values indatabase.ymlare used. This is somewhat unexpected, if one were to set values such aspoolin theproduction:group ofdatabase.ymlthey are ignored.There are many ways that Active Record initiates a connection today:
-
Stand Alone (without rails)
rake db:<tasks>ActiveRecord.establish_connection
-
With Rails
rake db:<tasks>rails <server> | <console>rails dbconsole
Now all of these behave exactly the same way. The best way to do this is to put all of this logic in one place so it is guaranteed to be used.
Here is the matrix of how this behavior works:
No database.yml No DATABASE_URL => Errordatabase.yml present No DATABASE_URL => Use database.yml configurationNo database.yml DATABASE_URL present => use DATABASE_URL configurationdatabase.yml present DATABASE_URL present => Merged into `url` sub key. If both specify `url` sub key, the `database.yml` `url` sub key "wins". If other paramaters `adapter` or `database` are specified in YAML, they are discarded as the `url` sub key "wins".Current implementation uses
ActiveRecord::Base.configurationsto resolve and merge all connection information before returning. This is achieved through a utility class:ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig.To understand the exact behavior of this class, it is best to review the behavior in
activerecord/test/cases/connection_adapters/connection_handler_test.rb.Richard Schneeman
-
-
Make
change_column_nullrevertable. Fixes #13576.Yves Senn, Nishant Modak, Prathamesh Sonpatki
-
Don't create/drop the test database if RAILS_ENV is specified explicitly.
Previously, when the environment was development, we would always create or drop both the test and development databases.
Now, if RAILS_ENV is explicitly defined as development, we don't create the test database.
Damien Mathieu
-
Initialize version on Migration objects so that it can be used in a migration, and it will be included in the announce message.
Dylan Thacker-Smith
-
change_tablenow uses the current adapter'supdate_table_definitionmethod to retrieve a specific table definition. This ensures thatchange_tableandcreate_tablewill use similar objects.Fixes #13577, #13503.
Nishant Modak, Prathamesh Sonpatki, Rafael Mendonça França
-
Fixed ActiveRecord::Store nil conversion TypeError when using YAML coder. In case the YAML passed as paramter is nil, uses an empty string.
Fixes #13570.
Thales Oliveira
-
Deprecate unused
ActiveRecord::Base.symbolized_base_classandActiveRecord::Base.symbolized_sti_namewithout replacement.Yves Senn
-
Since the
test_help.rbfile in Railties now automatically maintains your test schema, therake db:test:*tasks are deprecated. This doesn't stop you manually running other tasks on your test database if needed:rake db:schema:load RAILS_ENV=testJon Leighton
-
Fix presence validator for association when the associated record responds to
to_a.gmarik
-
Fixed regression on preload/includes with multiple arguments failing in certain conditions, raising a NoMethodError internally by calling
reflect_on_associationforNilClass:Class.Fixes #13437.
Vipul A M, khustochka
-
Add the ability to nullify the
enumcolumn.Example:
class Conversation < ActiveRecord::Base enum gender: [:female, :male] end Conversation::GENDER # => { female: 0, male: 1 } # conversation.update! gender: 0 conversation.female! conversation.female? # => true conversation.gender # => "female" # conversation.update! gender: nil conversation.gender = nil conversation.gender.nil? # => true conversation.gender # => nilAmr Tamimi
-
Connection specification now accepts a "url" key. The value of this key is expected to contain a database URL. The database URL will be expanded into a hash and merged.
Richard Schneeman
-
An
ArgumentErroris now raised on a call toRelation#where.not(nil).Example:
User.where.not(nil) # Before # => 'SELECT `users`.* FROM `users` WHERE (NOT (NULL))' # After # => ArgumentError, 'Invalid argument for .where.not(), got nil.'Kuldeep Aggarwal
-
Deprecated use of string argument as a configuration lookup in
ActiveRecord::Base.establish_connection. Instead, a symbol must be given.José Valim
-
Fixed
update_column,update_columns, andupdate_allto correctly serialize values forarray,hstoreandjsoncolumn types in PostgreSQL.Fixes #12261.
Tadas Tamosauskas, Carlos Antonio da Silva
-
Do not consider PostgreSQL array columns as number or text columns.
The code uses these checks in several places to know what to do with a particular column, for instance AR attribute query methods has a branch like this:
if column.number? !value.zero? endThis should never be true for array columns, since it would be the same as running [].zero?, which results in a NoMethodError exception.
Fixing this by ensuring that array columns in PostgreSQL never return true for number?/text? checks.
Carlos Antonio da Silva
-
When connecting to a non-existant database, the error:
ActiveRecord::NoDatabaseErrorwill now be raised. When being used with Rails the error message will include information on how to create a database:rake db:create. Supported adapters: postgresql, mysql, mysql2, sqlite3Richard Schneeman
-
Do not raise
'cannot touch on a new record object'exception on destroying already destroyedbelongs_toassociation withtouch: trueoption.Fixes #13445.
Example:
# Given Comment has belongs_to :post, touch: true comment.post.destroy comment.destroy # no longer raises an errorPaul Nikitochkin
-
Fix a bug when assigning an array containing string numbers to a PostgreSQL integer array column.
Fixes #13444.
Example:
# Given Book#ratings is of type :integer, array: true Book.new(ratings: [1, 2]) # worked before Book.new(ratings: ['1', '2']) # now works as wellDamien Mathieu
-
Fix
PostgreSQLinsert to properly extract table name from multiline string SQL.Previously, executing an insert SQL in
PostgreSQLwith a command like this:insert into articles( number) values( 5152 )would not work because the adapter was unable to extract the correct
articlestable name.Kuldeep Aggarwal
-
Correctly escape PostgreSQL arrays.
Fixes: CVE-2014-0080
-
Relationno longer has mutator methods like#map!and#delete_if. Convert to anArrayby calling#to_abefore using these methods.It intends to prevent odd bugs and confusion in code that call mutator methods directly on the
Relation.Example:
# Instead of this Author.where(name: 'Hank Moody').compact! # Now you have to do this authors = Author.where(name: 'Hank Moody').to_a authors.compact!Lauro Caetano
-
Better support for
where()conditions that use abelongs_toassociation name.Using the name of an association in
wherepreviously worked only if the value was a singleActiveRecord::Baseobject. e.g.Post.where(author: Author.first)Any other values, including
nil, would cause invalid SQL to be generated. This change supports arguments in thewherequery conditions where the key is abelongs_toassociation name and the value isnil, anArrayofActiveRecord::Baseobjects, or anActiveRecord::Relationobject.class Post < ActiveRecord::Base belongs_to :author endnilvalue finds records where the association is not set:Post.where(author: nil) # SELECT "posts".* FROM "posts" WHERE "posts"."author_id" IS NULLArrayvalues find records where the association foreign key matches the ids of the passed ActiveRecord models, resulting in the same query asPost.where(author_id: [1,2]):authors_array = [Author.find(1), Author.find(2)] Post.where(author: authors_array) # SELECT "posts".* FROM "posts" WHERE "posts"."author_id" IN (1, 2)ActiveRecord::Relationvalues find records using the same query asPost.where(author_id: Author.where(last_name: "Emde"))Post.where(author: Author.where(last_name: "Emde")) # SELECT "posts".* FROM "posts" # WHERE "posts"."author_id" IN ( # SELECT "authors"."id" FROM "authors" # WHERE "authors"."last_name" = 'Emde')Polymorphic
belongs_toassociations will continue to be handled appropriately, with the polymorphicassociation_typefield added to the query to match the base class of the value. This feature previously only worked when the value was a singleActveRecord::Base.class Post < ActiveRecord::Base belongs_to :author, polymorphic: true end Post.where(author: Author.where(last_name: "Emde")) # Generates a query similar to: Post.where(author_id: Author.where(last_name: "Emde"), author_type: "Author")Martin Emde
-
Respect temporary option when dropping tables with MySQL.
Normal DROP TABLE also works, but commits the transaction.
drop_table :temporary_table, temporary: trueCody Cutrer
-
Add option to create tables from a query.
create_table(:long_query, temporary: true, as: "SELECT * FROM orders INNER JOIN line_items ON order_id=orders.id")Generates:
CREATE TEMPORARY TABLE long_query AS SELECT * FROM orders INNER JOIN line_items ON order_id=orders.idCody Cutrer
-
db:test:cloneanddb:test:preparemust load Rails environment.db:test:cloneanddb:test:prepareuseActiveRecord::Base. configurations, so we need to load the Rails environment, otherwise the config wont be in place.arthurnn
-
Use the right column to type cast grouped calculations with custom expressions.
Fixes #13230.
Example:
# Before Account.group(:firm_name).sum('0.01 * credit_limit') # => { '37signals' => '0.5' } # After Account.group(:firm_name).sum('0.01 * credit_limit') # => { '37signals' => 0.5 }Paul Nikitochkin
-
Polymorphic
belongs_toassociations with thetouch: trueoption set update the timestamps of the old and new owner correctly when moved between owners of different types.Example:
class Rating < ActiveRecord::Base belongs_to :rateable, polymorphic: true, touch: true end rating = Rating.create rateable: Song.find(1) rating.update_attributes rateable: Book.find(2) # => timestamps of Song(1) and Book(2) are updatedSeverin Schoepke
-
Improve formatting of migration exception messages: make them easier to read with line breaks before/after, and improve the error for pending migrations.
John Bachir
-
Fix
lastwithoffsetto return the proper record instead of always the last one.Example:
Model.offset(4).last # => returns the 4th record from the end.Fixes #7441.
kostya, Lauro Caetano
-
type_to_sqlreturns aStringfor unmapped columns. This fixes an error when using unmapped PostgreSQL array types.Example:
change_colum :table, :column, :bigint, array: trueFixes #13146.
Jens Fahnenbruck, Yves Senn
-
Fix
QueryCacheto work with nested blocks, so that it will only clear the existing cache after leaving the outer block instead of clearing it right after the inner block is finished.Vipul A M
-
The ERB in fixture files is no longer evaluated in the context of the main object. Helper methods used by multiple fixtures should be defined on the class object returned by
ActiveRecord::FixtureSet.context_class.Victor Costan
-
Previously, the
has_onemacro incorrectly accepted thecounter_cacheoption, but never actually supported it. Now it will raise anArgumentErrorwhen usinghas_onewithcounter_cache.Godfrey Chan
-
Implement
rename_indexnatively for MySQL >= 5.7.Cody Cutrer
-
Fix bug when validating the uniqueness of an aliased attribute.
Fixes #12402.
Lauro Caetano
-
Update counter cache on a
has_manyrelationship regardless of default scope.Fixes #12952.
Uku Taht
-
rename_indexadds the new index before removing the old one. This allows to rename indexes on columns with a foreign key and prevents the following error:Cannot drop index 'index_engines_on_car_id': needed in a foreign key constraintCody Cutrer, Yves Senn
-
Raise
ActiveRecord::RecordNotDestroyedwhen a replaced child marked withdependent: destroyfails to be destroyed.Fixes #12812.
Brian Thomas Storti
-
Fix validation on uniqueness of empty association.
Evgeny Li
-
Make
ActiveRecord::Relation#unscopeaffect relations it is merged in to.Jon Leighton
-
Use strings to represent non-string
order_values.Yves Senn
-
Checks to see if the record contains the foreign key to set the inverse automatically.
Edo Balvers
-
Added
ActiveRecord::Base.to_paramfor convenient "pretty" URLs derived from a model's attribute or method.Example:
class User < ActiveRecord::Base to_param :name end user = User.find_by(name: 'Fancy Pants') user.id # => 123 user.to_param # => "123-fancy-pants"Javan Makhmali
-
Added
ActiveRecord::Base.no_touching, which allows ignoring touch on models.Example:
Post.no_touching do Post.first.touch endSam Stephenson, Damien Mathieu
-
Prevent the counter cache from being decremented twice when destroying a record on a
has_many :throughassociation.Fixes #11079.
Dmitry Dedov
-
Unify boolean type casting for
MysqlAdapterandMysql2Adapter.type_castwill return1fortrueand0forfalse.Fixes #11119.
Adam Williams, Yves Senn
-
Fix bug where
has_oneassociation record update result in crash, when replaced with itself.Fixes #12834.
Denis Redozubov, Sergio Cambra
-
Log bind variables after they are type casted. This makes it more transparent what values are actually sent to the database.
irb(main):002:0> Event.find("im-no-integer") # Before: ... WHERE "events"."id" = $1 LIMIT 1 [["id", "im-no-integer"]] # After: ... WHERE "events"."id" = $1 LIMIT 1 [["id", 0]]Yves Senn
-
Fix uninitialized constant
TransactionStateerror whenMarshall.loadis used on an Active Record result.Fixes #12790.
Jason Ayre
-
.unscopenow removes conditions specified indefault_scope.Jon Leighton
-
Added
ActiveRecord::QueryMethods#rewherewhich will overwrite an existing, named where condition.Examples:
Post.where(trashed: true).where(trashed: false) #=> WHERE `trashed` = 1 AND `trashed` = 0 Post.where(trashed: true).rewhere(trashed: false) #=> WHERE `trashed` = 0 Post.where(active: true).where(trashed: true).rewhere(trashed: false) #=> WHERE `active` = 1 AND `trashed` = 0DHH
-
Extend
ActiveRecord::Base#cache_keyto take an optional list of timestamp attributes of which the highest will be used.Example:
# last_reviewed_at will be used, if that's more recent than updated_at, or vice versa Person.find(5).cache_key(:updated_at, :last_reviewed_at)DHH
-
Added
ActiveRecord::Base#enumfor declaring enum attributes where the values map to integers in the database, but can be queried by name.Example:
class Conversation < ActiveRecord::Base enum status: [:active, :archived] end Conversation::STATUS # => { active: 0, archived: 1 } # conversation.update! status: 0 conversation.active! conversation.active? # => true conversation.status # => "active" # conversation.update! status: 1 conversation.archived! conversation.archived? # => true conversation.status # => "archived" # conversation.update! status: 1 conversation.status = :archivedDHH
-
ActiveRecord::Base#attribute_for_inspectnow truncates long arrays (more than 10 elements).Jan Bernacki
-
Allow for the name of the
schema_migrationstable to be configured.Jerad Phelps
-
Do not add to scope includes values from through associations. Fixed bug when providing
includesin through association scope, and fetching targets.Example:
class Vendor < ActiveRecord::Base has_many :relationships, -> { includes(:user) } has_many :users, through: :relationships end vendor = Vendor.first # Before vendor.users.to_a # => Raises exception: not found `:user` for `User` # After vendor.users.to_a # => No exception is raisedFixes #12242, #9517, #10240.
Paul Nikitochkin
-
Type cast json values on write, so that the value is consistent with reading from the database.
Example:
x = JsonDataType.new tags: {"string" => "foo", :symbol => :bar} # Before: x.tags # => {"string" => "foo", :symbol => :bar} # After: x.tags # => {"string" => "foo", "symbol" => "bar"}Severin Schoepke
-
ActiveRecord::Storeworks together with PostgreSQLhstorecolumns.Fixes #12452.
Yves Senn
-
Fix bug where
ActiveRecord::Storeused a globalHashto keep track of all registeredstored_attributes. Now every subclass ofActiveRecord::Basehas it's ownHash.Yves Senn
-
Save
has_oneassociation when primary key is manually set.Fixes #12302.
Lauro Caetano
-
Allow any version of BCrypt when using
has_secure_password.Mike Perham
-
Sub-query generated for
Relationpassed as array condition did not take in account bind values and have invalid syntax.Generate sub-query with inline bind values.
Fixes #12586.
Paul Nikitochkin
-
Fix a bug where rake db:structure:load crashed when the path contained spaces.
Kevin Mook
-
ActiveRecord::QueryMethods#unscopeunscopes negative equalityAllows you to call
#unscopeon a relation with negative equality operators, i.e.Arel::Nodes::NotInandArel::Nodes::NotEqualthat have been generated through the use ofwhere.not.Eric Hankins
-
Raise an exception when model without primary key calls
.find_with_ids.Shimpei Makimoto
-
Make
Relation#empty?useexists?instead ofcount.Szymon Nowak
-
rake db:structure:dumpno longer crashes when the port was specified asFixnum.Kenta Okamoto
-
NullRelation#plucktakes a list of columnsThe method signature in
NullRelationwas updated to mimic that inCalculations.Derek Prior
-
scope_chainshould not be mutated for other reflections.Currently
scope_chainuses same array for building differentscope_chainfor different associations. During processing these arrays are sometimes mutated and because of in-place mutation the changedscope_chainimpacts other reflections.Fix is to dup the value before adding to the
scope_chain.Fixes #3882.
Neeraj Singh
-
Prevent the inversed association from being reloaded on save.
Fixes #9499.
Dmitry Polushkin
-
Generate subquery for
Relationif it passed as array condition forwheremethod.Example:
# Before Blog.where('id in (?)', Blog.where(id: 1)) # => SELECT "blogs".* FROM "blogs" WHERE "blogs"."id" = 1 # => SELECT "blogs".* FROM "blogs" WHERE (id IN (1)) # After Blog.where('id in (?)', Blog.where(id: 1).select(:id)) # => SELECT "blogs".* FROM "blogs" # WHERE "blogs"."id" IN (SELECT "blogs"."id" FROM "blogs" WHERE "blogs"."id" = 1)Fixes #12415.
Paul Nikitochkin
-
For missed association exception message which is raised in
ActiveRecord::Associations::Preloaderclass added owner record class name in order to simplify to find problem code.Paul Nikitochkin
-
has_and_belongs_to_manyis now transparently implemented in terms ofhas_many :through. Behavior should remain the same, if not, it is a bug. -
create_savepoint,rollback_to_savepointandrelease_savepointaccept a savepoint name.Yves Senn
-
Make
next_migration_numberaccessible for third party generators.Yves Senn
-
Objects instantiated using a null relationship will now retain the attributes of the where clause.
Fixes #11676, #11675, #11376.
Paul Nikitochkin, Peter Brown, Nthalk
-
Fixed
ActiveRecord::Associations::CollectionAssociation#findwhen usinghas_manyassociation with:inverse_ofand finding an array of one element, it should return an array of one element too.arthurnn
-
Callbacks on has_many should access the in memory parent if a inverse_of is set.
arthurnn
-
ActiveRecord::ConnectionAdapters.string_to_timerespects string with timezone (e.g. Wed, 04 Sep 2013 20:30:00 JST).Fixes #12278.
kennyj
-
Calling
update_attributeswill now throw anArgumentErrorwhenever it gets anilargument. More specifically, it will throw an error if the argument that it gets passed does not respond to tostringify_keys.Example:
@my_comment.update_attributes(nil) # => raises ArgumentErrorJohn Wang
-
Deprecate
quoted_locking_columnmethod, which isn't used anywhere.kennyj
-
Migration dump UUID default functions to schema.rb.
Fixes #10751.
kennyj
-
Fixed a bug in
ActiveRecord::Associations::CollectionAssociation#find_by_scanwhen usinghas_manyassociation with:inverse_ofoption and UUID primary key.Fixes #10450.
kennyj
-
Fix: joins association, with defined in the scope block constraints by using several where constraints and at least of them is not
Arel::Nodes::Equality, generates invalid SQL expression.Fixes #11963.
Paul Nikitochkin
-
CollectionAssociation#first/#last(e.g.has_many) use aLIMITed query to fetch results rather than loading the entire collection.Lann Martin
-
Make possible to run SQLite rake tasks without the
Railsconstant defined.Damien Mathieu
-
Allow Relation#from to accept other relations with bind values.
Ryan Wallace
-
Fix inserts with prepared statements disabled.
Fixes #12023.
Rafael Mendonça França
-
Setting a has_one association on a new record no longer causes an empty transaction.
Dylan Thacker-Smith
-
Fix
AR::Relation#mergesometimes failing to preservereadonly(false)flag.thedarkone
-
Re-use
orderargument pre-processing forreorder.Paul Nikitochkin
-
Fix PredicateBuilder so polymorphic association keys in
whereclause can accept objects other than direct descendants ofActiveRecord::Base(decorated models, for example).Mikhail Dieterle
-
PostgreSQL adapter recognizes negative money values formatted with parentheses (eg.
($1.25) # => -1.25)). Fixes #11899.Yves Senn
-
Stop interpreting SQL 'string' columns as :string type because there is no common STRING datatype in SQL.
Ben Woosley
-
ActiveRecord::FinderMethods#exists?returnstrue/falsein all cases.Xavier Noria
-
Assign inet/cidr attribute with
nilvalue for invalid address.Example:
record = User.new record.logged_in_from_ip # is type of an inet or a cidr # Before: record.logged_in_from_ip = 'bad ip address' # raise exception # After: record.logged_in_from_ip = 'bad ip address' # do not raise exception record.logged_in_from_ip # => nil record.logged_in_from_ip_before_type_cast # => 'bad ip address'Paul Nikitochkin
-
add_to_targetnow accepts a second optionalskip_callbacksargumentIf truthy, it will skip the :before_add and :after_add callbacks.
Ben Woosley
-
Fix interactions between
:before_addcallbacks and nested attributes assignment ofhas_manyassociations, when the association was not yet loaded:-
A
:before_addcallback was being called when a nested attributes assignment assigned to an existing record. -
Nested Attributes assignment did not affect the record in the association target when a
:before_addcallback triggered the loading of the association
Jörg Schray
-
-
Allow enable_extension migration method to be revertible.
Eric Tipton
-
Type cast hstore values on write, so that the value is consistent with reading from the database.
Example:
x = Hstore.new tags: {"bool" => true, "number" => 5} # Before: x.tags # => {"bool" => true, "number" => 5} # After: x.tags # => {"bool" => "true", "number" => "5"}Yves Senn , Severin Schoepke
-
Fix multidimensional PostgreSQL arrays containing non-string items.
Yves Senn
-
Fixes bug when using includes combined with select, the select statement was overwritten.
Fixes #11773.
Edo Balvers
-
Load fixtures from linked folders.
Kassio Borges
-
Create a directory for sqlite3 file if not present on the system.
Richard Schneeman
-
Removed redundant override of
xmlcolumn definition for PostgreSQL, in order to usexmlcolumn type instead oftext.Paul Nikitochkin, Michael Nikitochkin
-
Revert
ActiveRecord::Relation#orderchange that make new order prepend the old one.Before:
User.order("name asc").order("created_at desc") # SELECT * FROM users ORDER BY created_at desc, name ascAfter:
User.order("name asc").order("created_at desc") # SELECT * FROM users ORDER BY name asc, created_at descThis also affects order defined in
default_scopeor any kind of associations. -
Add ability to define how a class is converted to Arel predicates. For example, adding a very vendor specific regex implementation:
regex_handler = proc do |column, value| Arel::Nodes::InfixOperation.new('~', column, value.source) end ActiveRecord::PredicateBuilder.register_handler(Regexp, regex_handler)Sean Griffin & @joannecheng
-
Don't allow
quote_valueto be called without a column.Some adapters require column information to do their job properly. By enforcing the provision of the column for this internal method we ensure that those using adapters that require column information will always get the proper behavior.
Ben Woosley
-
When using optimistic locking,
updatewas not passing the column toquote_valueto allow the connection adapter to properly determine how to quote the value. This was affecting certain databases that use specific column types.Fixes #6763.
Alfred Wong
-
rescue from all exceptions in
ConnectionManagement#callFixes #11497.
As
ActiveRecord::ConnectionAdapters::ConnectionManagementmiddleware does not rescue from Exception (but only from StandardError), the Connection Pool quickly runs out of connections when multiple erroneous Requests come in right after each other.Rescuing from all exceptions and not just StandardError, fixes this behaviour.
Vipul A M
-
change_columnfor PostgreSQL adapter respects the:arrayoption.Yves Senn
-
Remove deprecation warning from
attribute_missingfor attributes that are columns.Arun Agrawal
-
Remove extra decrement of transaction deep level.
Fixes #4566.
Paul Nikitochkin
-
Reset @column_defaults when assigning
locking_column. We had a potential problem. For example:class Post < ActiveRecord::Base self.column_defaults # if we call this unintentionally before setting locking_column ... self.locking_column = 'my_locking_column' end
Post.column_defaults["my_locking_column"] => nil # expected value is 0 !
kennyj
-
Remove extra select and update queries on save/touch/destroy ActiveRecord model with belongs to reflection with option
touch: true.Fixes #11288.
Paul Nikitochkin
-
Remove deprecated nil-passing to the following
SchemaCachemethods:primary_keys,tables,columnsandcolumns_hash.Yves Senn
-
Remove deprecated block filter from
ActiveRecord::Migrator#migrate.Yves Senn
-
Remove deprecated String constructor from
ActiveRecord::Migrator.Yves Senn
-
Remove deprecated
scopeuse without passing a callable object.Arun Agrawal
-
Remove deprecated
transaction_joinable=in favor ofbegin_transactionwith:joinableoption.Arun Agrawal
-
Remove deprecated
decrement_open_transactions.Arun Agrawal
-
Remove deprecated
increment_open_transactions.Arun Agrawal
-
Remove deprecated
PostgreSQLAdapter#outside_transaction?method. You can use#transaction_open?instead.Yves Senn
-
Remove deprecated
ActiveRecord::Fixtures.find_table_namein favor ofActiveRecord::Fixtures.default_fixture_model_name.Vipul A M
-
Removed deprecated
columns_for_removefromSchemaStatements.Neeraj Singh
-
Remove deprecated
SchemaStatements#distinct.Francesco Rodriguez
-
Move deprecated
ActiveRecord::TestCaseinto the rails test suite. The class is no longer public and is only used for internal Rails tests.Yves Senn
-
Removed support for deprecated option
:restrictfor:dependentin associations.Neeraj Singh
-
Removed support for deprecated
delete_sqlin associations.Neeraj Singh
-
Removed support for deprecated
insert_sqlin associations.Neeraj Singh
-
Removed support for deprecated
finder_sqlin associations.Neeraj Singh
-
Support array as root element in JSON fields.
Alexey Noskov & Francesco Rodriguez
-
Removed support for deprecated
counter_sqlin associations.Neeraj Singh
-
Do not invoke callbacks when
delete_allis called on collection.Method
delete_allshould not be invoking callbacks and this feature was deprecated in Rails 4.0. This is being removed.delete_allwill continue to honor the:dependentoption. However if:dependentvalue is:destroythen the:delete_alldeletion strategy for that collection will be applied.User can also force a deletion strategy by passing parameter to
delete_all. For example you can do@post.comments.delete_all(:nullify).Neeraj Singh
-
Calling default_scope without a proc will now raise
ArgumentError.Neeraj Singh
-
Removed deprecated method
type_cast_codefrom Column.Neeraj Singh
-
Removed deprecated options
delete_sqlandinsert_sqlfrom HABTM association.Removed deprecated options
finder_sqlandcounter_sqlfrom collection association.Neeraj Singh
-
Remove deprecated
ActiveRecord::Base#connectionmethod. Make sure to access it via the class.Yves Senn
-
Remove deprecation warning for
auto_explain_threshold_in_seconds.Yves Senn
-
Remove deprecated
:distinctoption fromRelation#count.Yves Senn
-
Removed deprecated methods
partial_updates,partial_updates?andpartial_updates=.Neeraj Singh
-
Removed deprecated method
scoped.Neeraj Singh
-
Removed deprecated method
default_scopes?.Neeraj Singh
-
Remove implicit join references that were deprecated in 4.0.
Example:
# before with implicit joins Comment.where('posts.author_id' => 7) # after Comment.references(:posts).where('posts.author_id' => 7)Yves Senn
-
Apply default scope when joining associations. For example:
class Post < ActiveRecord::Base default_scope -> { where published: true } end class Comment belongs_to :post endWhen calling
Comment.joins(:post), we expect to receive only comments on published posts, since that is the default scope for posts.Before this change, the default scope from
Postwas not applied, so we'd get comments on unpublished posts.Jon Leighton
-
Remove
activerecord-deprecated_findersas a dependency.Łukasz Strzałkowski
-
Remove Oracle / Sqlserver / Firebird database tasks that were deprecated in 4.0.
kennyj
-
find_eachnow returns anEnumeratorwhen called without a block, so that it can be chained with otherEnumerablemethods.Ben Woosley
-
ActiveRecord::Result.eachnow returns anEnumeratorwhen called without a block, so that it can be chained with otherEnumerablemethods.Ben Woosley
-
Flatten merged join_values before building the joins.
While joining_values special treatment is given to string values. By flattening the array it ensures that string values are detected as strings and not arrays.
Fixes #10669.
Neeraj Singh and iwiznia
-
Do not load all child records for inverse case.
currently
post.comments.find(Comment.first.id)would load all comments for the given post to set the inverse association.This has a huge performance penalty. Because if post has 100k records and all these 100k records would be loaded in memory even though the comment id was supplied.
Fix is to use in-memory records only if loaded? is true. Otherwise load the records using full sql.
Fixes #10509.
Neeraj Singh
-
inspecton Active Record model classes does not initiate a new connection. This means that callinginspect, when the database is missing, will no longer raise an exception. Fixes #10936.Example:
Author.inspect # => "Author(no database connection)"Yves Senn
-
Handle single quotes in PostgreSQL default column values. Fixes #10881.
Dylan Markow
-
Log the sql that is actually sent to the database.
If I have a query that produces sql
WHERE "users"."name" = 'a b'then in the log all the whitespace is being squeezed. So the sql that is printed in the log isWHERE "users"."name" = 'a b'.Do not squeeze whitespace out of sql queries. Fixes #10982.
Neeraj Singh
-
Fixture setup no longer depends on
ActiveRecord::Base.configurations. This is relevant whenENV["DATABASE_URL"]is used in place of adatabase.yml.Yves Senn
-
Fix mysql2 adapter raises the correct exception when executing a query on a closed connection.
Yves Senn
-
Ambiguous reflections are on :through relationships are no longer supported. For example, you need to change this:
class Author < ActiveRecord::Base has_many :posts has_many :taggings, through: :posts end class Post < ActiveRecord::Base has_one :tagging has_many :taggings end class Tagging < ActiveRecord::Base endTo this:
class Author < ActiveRecord::Base has_many :posts has_many :taggings, through: :posts, source: :tagging end class Post < ActiveRecord::Base has_one :tagging has_many :taggings end class Tagging < ActiveRecord::Base endAaron Patterson
-
Remove column restrictions for
count, let the database raise if the SQL is invalid. The previous behavior was untested and surprising for the user. Fixes #5554.Example:
User.select("name, username").count # Before => SELECT count(*) FROM users # After => ActiveRecord::StatementInvalid # you can still use `count(:all)` to perform a query unrelated to the # selected columns User.select("name, username").count(:all) # => SELECT count(*) FROM usersYves Senn
-
Rails now automatically detects inverse associations. If you do not set the
:inverse_ofoption on the association, then Active Record will guess the inverse association based on heuristics.Note that automatic inverse detection only works on
has_many,has_one, andbelongs_toassociations. Extra options on the associations will also prevent the association's inverse from being found automatically.The automatic guessing of the inverse association uses a heuristic based on the name of the class, so it may not work for all associations, especially the ones with non-standard names.
You can turn off the automatic detection of inverse associations by setting the
:inverse_ofoption tofalselike so:class Taggable < ActiveRecord::Base belongs_to :tag, inverse_of: false endJohn Wang
-
Fix
add_columnwitharrayoption when using PostgreSQL. Fixes #10432.Adam Anderson
-
Usage of
implicit_readonlyis being removed. Please usereadonlymethod explicitly to mark records asreadonly. Fixes #10615.Example:
user = User.joins(:todos).select("users.*, todos.title as todos_title").readonly(true).first user.todos_title = 'clean pet' user.save! # will raise errorYves Senn
-
Fix the
:primary_keyoption forhas_manyassociations.Fixes #10693.
Yves Senn
-
Fix bug where tiny types are incorrectly coerced as boolean when the length is more than 1.
Fixes #10620.
Aaron Patterson
-
Also support extensions in PostgreSQL 9.1. This feature has been supported since 9.1.
kennyj
-
Deprecate
ConnectionAdapters::SchemaStatements#distinct, as it is no longer used by internals.Ben Woosley
-
Fix pending migrations error when loading schema and
ActiveRecord::Base.table_name_prefixis not blank.Call
assume_migrated_upto_versionon connection to prevent it from first being picked up inmethod_missing.In the base class,
Migration,method_missingexpects the argument to be a table name, and callsproper_table_nameon the arguments before sending toconnection. Iftable_name_prefixortable_name_suffixis used, the schema version changes toprefix_version_suffix, breakingrake test:prepare.Fixes #10411.
Kyle Stevens
-
Method
read_attribute_before_type_castshould accept input as symbol.Neeraj Singh
-
Confirm a record has not already been destroyed before decrementing counter cache.
Ben Tucker
-
Fixed a bug in
ActiveRecord#sanitize_sql_hash_for_conditionsin whichself.classis an argument toPredicateBuilder#build_from_hashcausingPredicateBuilderto call non-existent methodClass#reflect_on_association.Zach Ohlgren
-
While removing index if column option is missing then raise IrreversibleMigration exception.
Following code should raise
IrreversibleMigration. But the code was failing since options is an array and not a hash.def change change_table :users do |t| t.remove_index [:name, :email] end endFix was to check if the options is a Hash before operating on it.
Fixes #10419.
Neeraj Singh
-
Do not overwrite manually built records during one-to-one nested attribute assignment
For one-to-one nested associations, if you build the new (in-memory) child object yourself before assignment, then the NestedAttributes module will not overwrite it, e.g.:
class Member < ActiveRecord::Base has_one :avatar accepts_nested_attributes_for :avatar def avatar super || build_avatar(width: 200) end end member = Member.new member.avatar_attributes = {icon: 'sad'} member.avatar.width # => 200Olek Janiszewski
-
fixes bug introduced by #3329. Now, when autosaving associations, deletions happen before inserts and saves. This prevents a 'duplicate unique value' database error that would occur if a record being created had the same value on a unique indexed field as that of a record being destroyed.
Johnny Holton
-
Handle aliased attributes in ActiveRecord::Relation.
When using symbol keys, ActiveRecord will now translate aliased attribute names to the actual column name used in the database:
With the model
class Topic alias_attribute :heading, :title endThe call
Topic.where(heading: 'The First Topic')should yield the same result as
Topic.where(title: 'The First Topic')This also applies to ActiveRecord::Relation::Calculations calls such as
Model.sum(:aliased)andModel.pluck(:aliased).This will not work with SQL fragment strings like
Model.sum('DISTINCT aliased').Godfrey Chan
-
Mute
psqloutput when running rake db:schema:load.Godfrey Chan
-
Trigger a save on
has_one association=(associate)when the associate contents have changed.Fixes #8856.
Chris Thompson
-
Abort a rake task when missing db/structure.sql like
db:schema:loadtask.kennyj
-
rake:db:test:prepare falls back to original environment after execution.
Slava Markevich
Please check 4-0-stable for previous changes.