CHANGELOG.md 31.6 KB
Newer Older
1
## Rails 4.0.0 (unreleased) ##
R
Rafael Mendonça França 已提交
2

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
*   Add `find_or_create_by`, `find_or_create_by!` and
    `find_or_initialize_by` methods to `Relation`.

    These are similar to the `first_or_create` family of methods, but
    the behaviour when a record is created is slightly different:

        User.where(first_name: 'Penélope').first_or_create

    will execute:

        User.where(first_name: 'Penélope').create

    Causing all the `create` callbacks to execute within the context of
    the scope. This could affect queries that occur within callbacks.

        User.find_or_create_by(first_name: 'Penélope')

    will execute:

        User.create(first_name: 'Penélope')

    Which obviously does not affect the scoping of queries within
    callbacks.

27 28 29 30 31 32 33 34 35 36 37
    The `find_or_create_by` version also reads better, frankly.

    If you need to add extra attributes during create, you can do one of:

        User.create_with(active: true).find_or_create_by(first_name: 'Jon')
        User.find_or_create_by(first_name: 'Jon') { |u| u.active = true }

    The `first_or_create` family of methods have been nodoc'ed in favour
    of this API. They may be deprecated in the future but their
    implementation is very small and it's probably not worth putting users
    through lots of annoying deprecation warnings.
38 39 40

    *Jon Leighton*

41 42 43 44 45
*   Fix bug with presence validation of associations. Would incorrectly add duplicated errors 
    when the association was blank. Bug introduced in 1fab518c6a75dac5773654646eb724a59741bc13.

    *Scott Willson*

46 47 48 49 50
*   Fix bug where sum(expression) returns string '0' for no matching records
    Fixes #7439

    *Tim Macfarlane*

51 52 53 54
*   PostgreSQL adapter correctly fetches default values when using multiple schemas and domains in a db. Fixes #7914

    *Arturo Pie*

55 56 57 58
*   Learn ActiveRecord::QueryMethods#order work with hash arguments

    When symbol or hash passed we convert it to Arel::Nodes::Ordering.
    If we pass invalid direction(like name: :DeSc) ActiveRecord::QueryMethods#order will raise an exception
59

60 61 62 63 64
        User.order(:name, email: :desc)
        # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC

    *Tima Maslyuchenko*

65 66 67 68 69 70 71 72 73 74 75 76
*   Rename `ActiveRecord::Fixtures` class to `ActiveRecord::FixtureSet`.
    Instances of this class normally hold a collection of fixtures (records)
    loaded either from a single YAML file, or from a file and a folder
    with the same name.  This change make the class name singular and makes
    the class easier to distinguish from the modules like
    `ActiveRecord::TestFixtures`, which operates on multiple fixture sets,
    or `DelegatingFixtures`, `::Fixtures`, etc.,
    and from the class `ActiveRecord::Fixture`, which corresponds to a single
    fixture.

    *Alexey Muranov*

77 78 79 80 81
*   The postgres adapter now supports tables with capital letters.
    Fix #5920

    *Yves Senn*

82 83
*   `CollectionAssociation#count` returns `0` without querying if the
    parent record is not persisted.
84 85 86

    Before:

87
        person.pets.count
88 89 90 91 92
        # SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" IS NULL
        # => 0

    After:

93
        person.pets.count
94 95 96 97 98
        # fires without sql query
        # => 0

    *Francesco Rodriguez*

99 100 101 102 103
*   Fix `reset_counters` crashing on `has_many :through` associations.
    Fix #7822.

    *lulalala*

J
Jon Leighton 已提交
104 105 106 107 108 109 110 111 112 113 114
*   Support for partial inserts.

    When inserting new records, only the fields which have been changed
    from the defaults will actually be included in the INSERT statement.
    The other fields will be populated by the database.

    This is more efficient, and also means that it will be safe to
    remove database columns without getting subsequent errors in running
    app processes (so long as the code in those processes doesn't
    contain any references to the removed column).

115 116 117 118
    The `partial_updates` configuration option is now renamed to
    `partial_writes` to reflect the fact that it now impacts both inserts
    and updates.

J
Jon Leighton 已提交
119 120
    *Jon Leighton*

121 122 123 124
*   Allow before and after validations to take an array of lifecycle events

    *John Foley*

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
*   Support for specifying transaction isolation level

    If your database supports setting the isolation level for a transaction, you can set
    it like so:

        Post.transaction(isolation: :serializable) do
          # ...
        end

    Valid isolation levels are:

    * `:read_uncommitted`
    * `:read_committed`
    * `:repeatable_read`
    * `:serializable`

    You should consult the documentation for your database to understand the
    semantics of these different levels:

    * http://www.postgresql.org/docs/9.1/static/transaction-iso.html
    * https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html

    An `ActiveRecord::TransactionIsolationError` will be raised if:

    * The adapter does not support setting the isolation level
    * You are joining an existing open transaction
    * You are creating a nested (savepoint) transaction

    The mysql, mysql2 and postgresql adapters support setting the transaction
    isolation level. However, support is disabled for mysql versions below 5,
    because they are affected by a bug (http://bugs.mysql.com/bug.php?id=39170)
    which means the isolation level gets persisted outside the transaction.

    *Jon Leighton*

160 161 162 163 164 165 166 167 168 169
*   `ActiveModel::ForbiddenAttributesProtection` is included by default
    in Active Record models. Check the docs of `ActiveModel::ForbiddenAttributesProtection`
    for more details.

    *Guillermo Iguaran*

*   Remove integration between Active Record and
    `ActiveModel::MassAssignmentSecurity`, `protected_attributes` gem
    should be added to use `attr_accessible`/`attr_protected`. Mass
    assignment options has been removed from all the AR methods that
170
    used it (ex. `AR::Base.new`, `AR::Base.create`, `AR::Base#update_attributes`, etc).
171 172 173

    *Guillermo Iguaran*

174 175 176 177 178 179 180 181 182 183 184 185 186 187
*   Fix the return of querying with an empty hash.
    Fix #6971.

        User.where(token: {})

    Before:

        #=> SELECT * FROM users;

    After:

        #=> SELECT * FROM users WHERE 1 = 2;

    *Damien Mathieu*
D
Damien Mathieu 已提交
188

189 190 191
*   Fix creation of through association models when using `collection=[]`
    on a `has_many :through` association from an unsaved model.
    Fix #7661.
192 193 194

    *Ernie Miller*

K
kennyj 已提交
195
*   Explain only normal CRUD sql (select / update / insert / delete).
196 197
    Fix problem that explains unexplainable sql.
    Closes #7544 #6458.
K
kennyj 已提交
198 199 200

    *kennyj*

M
Matt Jones 已提交
201 202 203 204 205 206
*   You can now override the generated accessor methods for stored attributes
    and reuse the original behavior with `read_store_attribute` and `write_store_attribute`,
    which are counterparts to `read_attribute` and `write_attribute`.

    *Matt Jones*

207
*   Accept belongs_to (including polymorphic) association keys in queries.
208 209 210

    The following queries are now equivalent:

211 212
        Post.where(author: author)
        Post.where(author_id: author)
213

214 215
        PriceEstimate.where(estimate_of: treasure)
        PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
216 217 218

    *Peter Brown*

219 220 221 222 223
*   Use native `mysqldump` command instead of `structure_dump` method
    when dumping the database structure to a sql file. Fixes #5547.

    *kennyj*

224
*   PostgreSQL inet and cidr types are converted to `IPAddr` objects.
225

226 227 228 229 230 231 232 233
    *Dan McClain*

*   PostgreSQL array type support. Any datatype can be used to create an
    array column, with full migration and schema dumper support.

    To declare an array column, use the following syntax:

        create_table :table_with_arrays do |t|
234
          t.integer :int_array, array: true
235
          # integer[]
236
          t.integer :int_array, array: true, length: 2
237
          # smallint[]
238
          t.string :string_array, array: true, length: 30
239
          # char varying(30)[]
240
        end
241

242
    This respects any other migration detail (limits, defaults, etc).
X
Xavier Noria 已提交
243
    Active Record will serialize and deserialize the array columns on
244 245 246 247 248 249 250 251
    their way to and from the database.

    One thing to note: PostgreSQL does not enforce any limits on the
    number of elements, and any array can be multi-dimensional. Any
    array that is multi-dimensional must be rectangular (each sub array
    must have the same number of elements as its siblings).

    If the `pg_array_parser` gem is available, it will be used when
252
    parsing PostgreSQL's array representation.
253 254 255

    *Dan McClain*

256 257
*   Attribute predicate methods, such as `article.title?`, will now raise
    `ActiveModel::MissingAttributeError` if the attribute being queried for
258
    truthiness was not read from the database, instead of just returning `false`.
259 260 261

    *Ernie Miller*

262 263 264 265
*   `ActiveRecord::SchemaDumper` uses Ruby 1.9 style hash, which means that the
    schema.rb file will be generated using this new syntax from now on.

    *Konstantin Shabanov*
266

267 268 269
*   Map interval with precision to string datatype in PostgreSQL. Fixes #7518.

    *Yves Senn*
270

271 272 273
*   Fix eagerly loading associations without primary keys. Fixes #4976.

    *Kelley Reynolds*
274

275 276 277 278 279 280
*   Rails now raise an exception when you're trying to run a migration that has an invalid
    file name. Only lower case letters, numbers, and '_' are allowed in migration's file name.
    Please see #7419 for more details.

    *Jan Bernacki*

M
Matt Jones 已提交
281
*   Fix bug when calling `store_accessor` multiple times.
282 283 284 285 286 287 288 289 290
    Fixes #7532.

    *Matt Jones*

*   Fix store attributes that show the changes incorrectly.
    Fixes #7532.

    *Matt Jones*

291 292 293 294
*   Fix `ActiveRecord::Relation#pluck` when columns or tables are reserved words.

    *Ian Lesperance*

295
*   Allow JSON columns to be created in PostgreSQL and properly encoded/decoded.
296 297 298 299
    to/from database.

    *Dickson S. Guedes*

300
*   Fix time column type casting for invalid time string values to correctly return `nil`.
301 302 303

    *Adam Meehan*

304
*   Allow to pass Symbol or Proc into `:limit` option of #accepts_nested_attributes_for.
M
Mikhail Dieterle 已提交
305 306 307

    *Mikhail Dieterle*

308
*   ActiveRecord::SessionStore has been extracted from Active Record as `activerecord-session_store`
309 310 311
    gem. Please read the `README.md` file on the gem for the usage.

    *Prem Sichanugrist*
312

313 314 315 316 317 318
*   Fix `reset_counters` when there are multiple `belongs_to` association with the
    same foreign key and one of them have a counter cache.
    Fixes #5200.

    *Dave Desrochers*

319 320 321 322
*   `serialized_attributes` and `_attr_readonly` become class method only. Instance reader methods are deprecated.

    *kennyj*

323 324 325 326 327
*   Round usec when comparing timestamp attributes in the dirty tracking.
    Fixes #6975.

    *kennyj*

328 329 330 331
*   Use inversed parent for first and last child of has_many association.

    *Ravil Bayramgalin*

332 333 334 335 336 337
*   Fix Column.microseconds and Column.fast_string_to_date to avoid converting
    timestamp seconds to a float, since it occasionally results in inaccuracies
    with microsecond-precision times. Fixes #7352.

    *Ari Pollak*

338 339 340 341 342
*   Fix AR#dup to nullify the validation errors in the dup'ed object. Previously the original
    and the dup'ed object shared the same errors.

    * Christian Seiler*

343 344 345 346
*   Raise `ArgumentError` if list of attributes to change is empty in `update_all`.

    *Roman Shatsov*

347 348 349 350 351
*   Fix AR#create to return an unsaved record when AR::RecordInvalid is
    raised. Fixes #3217.

    *Dave Yeu*

352 353
*   Fixed table name prefix that is generated in engines for namespaced models.

354 355
    *Wojciech Wnętrzak*

356
*   Make sure `:environment` task is executed before `db:schema:load` or `db:structure:load`.
R
Rafael Mendonça França 已提交
357 358 359 360
    Fixes #4772.

    *Seamus Abshere*

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
*   Allow Relation#merge to take a proc.

    This was requested by DHH to allow creating of one's own custom
    association macros.

    For example:

        module Commentable
          def has_many_comments(extra)
            has_many :comments, -> { where(:foo).merge(extra) }
          end
        end

        class Post < ActiveRecord::Base
          extend Commentable
          has_many_comments -> { where(:bar) }
        end

    *Jon Leighton*

381
*   Add CollectionProxy#scope.
J
Jon Leighton 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398

    This can be used to get a Relation from an association.

    Previously we had a #scoped method, but we're deprecating that for
    AR::Base, so it doesn't make sense to have it here.

    This was requested by DHH, to facilitate code like this:

        Project.scope.order('created_at DESC').page(current_page).tagged_with(@tag).limit(5).scoping do
          @topics      = @project.topics.scope
          @todolists   = @project.todolists.scope
          @attachments = @project.attachments.scope
          @documents   = @project.documents.scope
        end

    *Jon Leighton*

399
*   Add `Relation#load`.
J
Jon Leighton 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413

    This method explicitly loads the records and then returns `self`.

    Rather than deciding between "do I want an array or a relation?",
    most people are actually asking themselves "do I want to eager load
    or lazy load?" Therefore, this method provides a way to explicitly
    eager-load without having to switch from a `Relation` to an array.

    Example:

        @posts = Post.where(published: true).load

    *Jon Leighton*

414 415 416 417 418 419 420 421 422
*   `Relation#order`: make new order prepend old one.

        User.order("name asc").order("created_at desc")
        # SELECT * FROM users ORDER BY created_at desc, name asc

    This also affects order defined in `default_scope` or any kind of associations.

    *Bogdan Gusiev*

423
*   `Model.all` now returns an `ActiveRecord::Relation`, rather than an
424
    array of records. Use `Relation#to_a` if you really want an array.
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

    In some specific cases, this may cause breakage when upgrading.
    However in most cases the `ActiveRecord::Relation` will just act as a
    lazy-loaded array and there will be no problems.

    Note that calling `Model.all` with options (e.g.
    `Model.all(conditions: '...')` was already deprecated, but it will
    still return an array in order to make the transition easier.

    `Model.scoped` is deprecated in favour of `Model.all`.

    `Relation#all` still returns an array, but is deprecated (since it
    would serve no purpose if we made it return a `Relation`).

    *Jon Leighton*

441 442 443 444 445 446 447
*   `:finder_sql` and `:counter_sql` options on collection associations
    are deprecated. Please transition to using scopes.

    *Jon Leighton*

*   `:insert_sql` and `:delete_sql` options on `has_and_belongs_to_many`
    associations are deprecated. Please transition to using `has_many
448
    :through`.
449 450 451

    *Jon Leighton*

452 453 454 455 456 457 458 459 460 461 462
*   Added `#update_columns` method which updates the attributes from
    the passed-in hash without calling save, hence skipping validations and
    callbacks. `ActiveRecordError` will be raised when called on new objects
    or when at least one of the attributes is marked as read only.

        post.attributes # => {"id"=>2, "title"=>"My title", "body"=>"My content", "author"=>"Peter"}
        post.update_columns(title: 'New title', author: 'Sebastian') # => true
        post.attributes # => {"id"=>2, "title"=>"New title", "body"=>"My content", "author"=>"Sebastian"}

    *Sebastian Martinez + Rafael Mendonça França*

463 464 465
*   The migration generator now creates a join table with (commented) indexes every time
    the migration name contains the word `join_table`:

466
        rails g migration create_join_table_for_artists_and_musics artist_id:index music_id
467 468 469

    *Aleksey Magusev*

470 471
*   Add `add_reference` and `remove_reference` schema statements. Aliases, `add_belongs_to`
    and `remove_belongs_to` are acceptable. References are reversible.
472

473
    Examples:
474 475 476

        # Create a user_id column
        add_reference(:products, :user)
477
        # Create a supplier_id, supplier_type columns and appropriate index
478 479 480 481 482 483
        add_reference(:products, :supplier, polymorphic: true, index: true)
        # Remove polymorphic reference
        remove_reference(:products, :supplier, polymorphic: true)

    *Aleksey Magusev*

484 485 486 487 488 489 490
*   Add `:default` and `:null` options to `column_exists?`.

        column_exists?(:testings, :taggable_id, :integer, null: false)
        column_exists?(:testings, :taggable_type, :string, default: 'Photo')

    *Aleksey Magusev*

491 492
*   `ActiveRecord::Relation#inspect` now makes it clear that you are
    dealing with a `Relation` object rather than an array:.
493

494
        User.where(age: 30).inspect
495
        # => <ActiveRecord::Relation [#<User ...>, #<User ...>, ...]>
B
Brian Cardarella 已提交
496

497
        User.where(age: 30).to_a.inspect
498
        # => [#<User ...>, #<User ...>]
499

500 501 502
    The number of records displayed will be limited to 10.

    *Brian Cardarella, Jon Leighton & Damien Mathieu*
B
Brian Cardarella 已提交
503

504
*   Add `collation` and `ctype` support to PostgreSQL. These are available for PostgreSQL 8.4 or later.
505 506
    Example:

507 508 509 510 511 512 513 514 515
        development:
          adapter: postgresql
          host: localhost
          database: rails_development
          username: foo
          password: bar
          encoding: UTF8
          collation: ja_JP.UTF8
          ctype: ja_JP.UTF8
516 517 518

    *kennyj*

519 520 521 522 523 524 525
*   Changed validates_presence_of on an association so that children objects
    do not validate as being present if they are marked for destruction. This
    prevents you from saving the parent successfully and thus putting the parent
    in an invalid state.

    *Nick Monje & Brent Wheeldon*

E
Egor Lynko 已提交
526 527 528 529
*   `FinderMethods#exists?` now returns `false` with the `false` argument.

    *Egor Lynko*

530 531 532 533 534 535 536 537 538 539 540 541
*   Added support for specifying the precision of a timestamp in the postgresql
    adapter. So, instead of having to incorrectly specify the precision using the
    `:limit` option, you may use `:precision`, as intended. For example, in a migration:

        def change
          create_table :foobars do |t|
            t.timestamps :precision => 0
          end
        end

    *Tony Schneider*

542
*   Allow `ActiveRecord::Relation#pluck` to accept multiple columns. Returns an
543
    array of arrays containing the typecasted values:
544 545 546 547 548 549 550

        Person.pluck(:id, :name)
        # SELECT people.id, people.name FROM people
        # [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]

    *Jeroen van Ingen & Carlos Antonio da Silva*

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
*   Improve the derivation of HABTM join table name to take account of nesting.
    It now takes the table names of the two models, sorts them lexically and
    then joins them, stripping any common prefix from the second table name.

    Some examples:

        Top level models (Category <=> Product)
        Old: categories_products
        New: categories_products

        Top level models with a global table_name_prefix (Category <=> Product)
        Old: site_categories_products
        New: site_categories_products

        Nested models in a module without a table_name_prefix method (Admin::Category <=> Admin::Product)
        Old: categories_products
        New: categories_products

        Nested models in a module with a table_name_prefix method (Admin::Category <=> Admin::Product)
        Old: categories_products
        New: admin_categories_products

        Nested models in a parent model (Catalog::Category <=> Catalog::Product)
        Old: categories_products
        New: catalog_categories_products

        Nested models in different parent models (Catalog::Category <=> Content::Page)
        Old: categories_pages
        New: catalog_categories_content_pages

    *Andrew White*

583
*   Move HABTM validity checks to `ActiveRecord::Reflection`. One side effect of
584 585 586 587 588 589
    this is to move when the exceptions are raised from the point of declaration
    to when the association is built. This is consistant with other association
    validity checks.

    *Andrew White*

590
*   Added `stored_attributes` hash which contains the attributes stored using
591
    `ActiveRecord::Store`. This allows you to retrieve the list of attributes
592
    you've defined.
593

594 595 596 597 598 599 600
       class User < ActiveRecord::Base
         store :settings, accessors: [:color, :homepage]
       end

       User.stored_attributes[:settings] # [:color, :homepage]

    *Joost Baaij & Carlos Antonio da Silva*
601

602 603 604 605 606 607
*   PostgreSQL default log level is now 'warning', to bypass the noisy notice
    messages. You can change the log level using the `min_messages` option
    available in your config/database.yml.

    *kennyj*

608 609 610
*   Add uuid datatype support to PostgreSQL adapter.

    *Konstantin Shabanov*
611

612
*   Added `ActiveRecord::Migration.check_pending!` that raises an error if
613 614 615
    migrations are pending.

    *Richard Schneeman*
616

617 618 619 620 621
*   Added `#destroy!` which acts like `#destroy` but will raise an
    `ActiveRecord::RecordNotDestroyed` exception instead of returning `false`.

    *Marc-André Lafortune*

622 623 624
*   Allow blocks for `count` with `ActiveRecord::Relation`, to work similar as
    `Array#count`:

625
        Person.where("age > 26").count { |person| person.gender == 'female' }
626 627 628

    *Chris Finne & Carlos Antonio da Silva*

629 630 631 632 633 634 635 636 637 638 639 640 641
*   Added support to `CollectionAssociation#delete` for passing `fixnum`
    or `string` values as record ids. This finds the records responding
    to the `id` and executes delete on them.

        class Person < ActiveRecord::Base
          has_many :pets
        end

        person.pets.delete("1") # => [#<Pet id: 1>]
        person.pets.delete(2, 3) # => [#<Pet id: 2>, #<Pet id: 3>]

    *Francesco Rodriguez*

642 643 644 645 646 647 648 649 650 651
*   Deprecated most of the 'dynamic finder' methods. All dynamic methods
    except for `find_by_...` and `find_by_...!` are deprecated. Here's
    how you can rewrite the code:

      * `find_all_by_...` can be rewritten using `where(...)`
      * `find_last_by_...` can be rewritten using `where(...).last`
      * `scoped_by_...` can be rewritten using `where(...)`
      * `find_or_initialize_by_...` can be rewritten using
        `where(...).first_or_initialize`
      * `find_or_create_by_...` can be rewritten using
652
        `find_or_create_by(...)` or where(...).first_or_create`
653
      * `find_or_create_by_...!` can be rewritten using
654
        `find_or_create_by!(...) or `where(...).first_or_create!`
655 656

    The implementation of the deprecated dynamic finders has been moved
657
    to the `activerecord-deprecated_finders` gem. See below for details.
658 659 660 661 662 663 664

    *Jon Leighton*

*   Deprecated the old-style hash based finder API. This means that
    methods which previously accepted "finder options" no longer do. For
    example this:

665
        Post.find(:all, conditions: { comments_count: 10 }, limit: 5)
666 667 668 669 670 671 672

    Should be rewritten in the new style which has existed since Rails 3:

        Post.where(comments_count: 10).limit(5)

    Note that as an interim step, it is possible to rewrite the above as:

673
        Post.all.merge(where: { comments_count: 10 }, limit: 5)
674 675 676 677

    This could save you a lot of work if there is a lot of old-style
    finder usage in your application.

678
    `Relation#merge` now accepts a hash of
679 680 681 682
    options, but they must be identical to the names of the equivalent
    finder method. These are mostly identical to the old-style finder
    option names, except in the following cases:

683 684 685
      * `:conditions` becomes `:where`.
      * `:include` becomes `:includes`.
      * `:extend` becomes `:extending`.
686 687

    The code to implement the deprecated features has been moved out to
688
    the `activerecord-deprecated_finders` gem. This gem is a dependency
689 690 691 692 693 694 695
    of Active Record in Rails 4.0. It will no longer be a dependency
    from Rails 4.1, but if your app relies on the deprecated features
    then you can add it to your own Gemfile. It will be maintained by
    the Rails core team until Rails 5.0 is released.

    *Jon Leighton*

J
Johannes Barre 已提交
696 697 698 699
*   It's not possible anymore to destroy a model marked as read only.

    *Johannes Barre*

700
*   Added ability to ActiveRecord::Relation#from to accept other ActiveRecord::Relation objects.
701 702 703 704 705 706

      Record.from(subquery)
      Record.from(subquery, :a)

    *Radoslav Stankov*

707 708 709 710 711 712
*   Added custom coders support for ActiveRecord::Store. Now you can set
    your custom coder like this:

        store :settings, accessors: [ :color, :homepage ], coder: JSON

    *Andrey Voronkov*
713

714 715 716 717 718 719
*   `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by
    default to avoid silent data loss. This can be disabled by specifying
    `strict: false` in your `database.yml`.

    *Michael Pearson*

720
*   Added default order to `first` to assure consistent results among
721
    different database engines. Introduced `take` as a replacement to
722 723 724 725
    the old behavior of `first`.

    *Marcelo Silveira*

726
*   Added an `:index` option to automatically create indexes for references
727 728 729 730 731 732 733
    and belongs_to statements in migrations.

    The `references` and `belongs_to` methods now support an `index`
    option that receives either a boolean value or an options hash
    that is identical to options available to the add_index method:

      create_table :messages do |t|
734
        t.references :person, index: true
735 736 737 738 739 740 741 742 743 744 745
      end

      Is the same as:

      create_table :messages do |t|
        t.references :person
      end
      add_index :messages, :person_id

    Generators have also been updated to use the new syntax.

746
    *Joshua Wood*
747

748 749 750 751 752 753 754
*   Added bang methods for mutating `ActiveRecord::Relation` objects.
    For example, while `foo.where(:bar)` will return a new object
    leaving `foo` unchanged, `foo.where!(:bar)` will mutate the foo
    object

    *Jon Leighton*

755 756 757 758 759 760 761 762 763 764
*   Added `#find_by` and `#find_by!` to mirror the functionality
    provided by dynamic finders in a way that allows dynamic input more
    easily:

        Post.find_by name: 'Spartacus', rating: 4
        Post.find_by "published_at < ?", 2.weeks.ago
        Post.find_by! name: 'Spartacus'

    *Jon Leighton*

G
Guillermo Iguaran 已提交
765 766 767 768 769
*   Added ActiveRecord::Base#slice to return a hash of the given methods with
    their names as keys and returned values as values.

    *Guillermo Iguaran*

J
Jon Leighton 已提交
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
*   Deprecate eager-evaluated scopes.

    Don't use this:

        scope :red, where(color: 'red')
        default_scope where(color: 'red')

    Use this:

        scope :red, -> { where(color: 'red') }
        default_scope { where(color: 'red') }

    The former has numerous issues. It is a common newbie gotcha to do
    the following:

        scope :recent, where(published_at: Time.now - 2.weeks)

    Or a more subtle variant:

        scope :recent, -> { where(published_at: Time.now - 2.weeks) }
        scope :recent_red, recent.where(color: 'red')

    Eager scopes are also very complex to implement within Active
    Record, and there are still bugs. For example, the following does
    not do what you expect:

        scope :remove_conditions, except(:where)
        where(...).remove_conditions # => still has conditions

    *Jon Leighton*

801 802 803 804 805 806 807 808 809 810
*   Remove IdentityMap

    IdentityMap has never graduated to be an "enabled-by-default" feature, due
    to some inconsistencies with associations, as described in this commit:

       https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6

    Hence the removal from the codebase, until such issues are fixed.

    *Carlos Antonio da Silva*
C
Carlos Antonio da Silva 已提交
811

812 813 814 815 816 817 818 819 820 821 822
*   Added the schema cache dump feature.

    `Schema cache dump` feature was implemetend. This feature can dump/load internal state of `SchemaCache` instance
    because we want to boot rails more quickly when we have many models.

    Usage notes:

      1) execute rake task.
      RAILS_ENV=production bundle exec rake db:schema:cache:dump
      => generate db/schema_cache.dump

823
      2) add config.active_record.use_schema_cache_dump = true in config/production.rb. BTW, true is default.
824 825 826

      3) boot rails.
      RAILS_ENV=production bundle exec rails server
827
      => use db/schema_cache.dump
828 829 830 831 832 833 834

      4) If you remove clear dumped cache, execute rake task.
      RAILS_ENV=production bundle exec rake db:schema:cache:clear
      => remove db/schema_cache.dump

    *kennyj*

835
*   Added support for partial indices to PostgreSQL adapter.
836 837 838 839

    The `add_index` method now supports a `where` option that receives a
    string with the partial index criteria.

840
        add_index(:accounts, :code, where: 'active')
841

842
        Generates
843

844
        CREATE INDEX index_accounts_on_code ON accounts(code) WHERE active
845 846 847

    *Marcelo Silveira*

848
*   Implemented ActiveRecord::Relation#none method.
849 850 851 852 853 854 855 856 857 858

    The `none` method returns a chainable relation with zero records
    (an instance of the NullRelation class).

    Any subsequent condition chained to the returned relation will continue
    generating an empty relation and will not fire any query to the database.

    *Juanjo Bazán*

*   Added the `ActiveRecord::NullRelation` class implementing the null
859
    object pattern for the Relation class.
860

861 862 863
    *Juanjo Bazán*

*   Added new `dependent: :restrict_with_error` option. This will add
864
    an error to the model, rather than raising an exception.
865

866 867
    The `:restrict` option is renamed to `:restrict_with_exception` to
    make this distinction explicit.
868

869
    *Manoj Kumar & Jon Leighton*
870

871
*   Added `create_join_table` migration helper to create HABTM join tables.
872 873 874

        create_join_table :products, :categories
        # =>
875 876 877
        # create_table :categories_products, id: false do |td|
        #   td.integer :product_id,  null: false
        #   td.integer :category_id, null: false
878 879 880 881
        # end

    *Rafael Mendonça França*

882
*   The primary key is always initialized in the @attributes hash to `nil` (unless
883
    another value has been specified).
884

885 886
    *Aaron Paterson*

887 888 889 890 891 892 893 894 895 896
*   In previous releases, the following would generate a single query with
    an `OUTER JOIN comments`, rather than two separate queries:

        Post.includes(:comments)
            .where("comments.name = 'foo'")

    This behaviour relies on matching SQL string, which is an inherently
    flawed idea unless we write an SQL parser, which we do not wish to
    do.

897 898 899 900
    Therefore, it is now deprecated.

    To avoid deprecation warnings and for future compatibility, you must
    explicitly state which tables you reference, when using SQL snippets:
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

        Post.includes(:comments)
            .where("comments.name = 'foo'")
            .references(:comments)

    Note that you do not need to explicitly specify references in the
    following cases, as they can be automatically inferred:

        Post.where(comments: { name: 'foo' })
        Post.where('comments.name' => 'foo')
        Post.order('comments.name')

    You also do not need to worry about this unless you are doing eager
    loading. Basically, don't worry unless you see a deprecation warning
    or (in future releases) an SQL error due to a missing JOIN.

917
    *Jon Leighton*
918

919
*   Support for the `schema_info` table has been dropped. Please
920 921
    switch to `schema_migrations`.

922 923 924
    *Aaron Patterson*

*   Connections *must* be closed at the end of a thread. If not, your
925 926
    connection pool can fill and an exception will be raised.

927 928
    *Aaron Patterson*

929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
*   Added the `ActiveRecord::Model` module which can be included in a
    class as an alternative to inheriting from `ActiveRecord::Base`:

        class Post
          include ActiveRecord::Model
        end

    Please note:

      * Up until now it has been safe to assume that all AR models are
        descendants of `ActiveRecord::Base`. This is no longer a safe
        assumption, but it may transpire that there are areas of the
        code which still make this assumption. So there may be
        'teething difficulties' with this feature. (But please do try it
        and report bugs.)

      * Plugins & libraries etc that add methods to `ActiveRecord::Base`
        will not be compatible with `ActiveRecord::Model`. Those libraries
        should add to `ActiveRecord::Model` instead (which is included in
948 949 950 951 952 953 954 955
        `Base`). This should be done using the `:active_record_model`
        load hook, which executes before `ActiveRecord::Base` loads:

            ActiveSupport.on_load(:active_record_model) do
              include MyPlugin
            end

        Or better still, avoid monkey-patching AR and instead
956 957 958 959 960 961 962 963
        provide a module that users can include where they need it.

      * To minimise the risk of conflicts with other code, it is
        advisable to include `ActiveRecord::Model` early in your class
        definition.

    *Jon Leighton*

964 965
*   PostgreSQL hstore records can be created.

966 967
    *Aaron Patterson*

968 969
*   PostgreSQL hstore types are automatically deserialized from the database.

970 971
    *Aaron Patterson*

X
Xavier Noria 已提交
972
Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activerecord/CHANGELOG.md) for previous changes.