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

3 4 5 6 7 8
*   The `#append` method for collection associations behaves like`<<`.
    `#prepend` is not defined and `<<` or `#append` should be used.
    Fixes #7364.

    *Yves Senn*

9
*   Added support for creating a table via Rails migration generator.
10
    For example,
11 12 13

        rails g migration create_books title:string content:text

14 15
    will generate a migration that creates a table called books with
    the listed attributes, without creating a model.
16 17 18

    *Sammy Larbi*

19 20 21
*   Fix bug that raises the wrong exception when the exception handled by PostgreSQL adapter
    doesn't respond to `#result`.
    Fixes #8617.
22 23 24

    *kennyj*

25 26 27 28 29 30 31 32 33 34 35 36
*   Support PostgreSQL specific column types when using `change_table`.
    Fixes #9480.

    Example:

        change_table :authors do |t|
          t.hstore :books
          t.json :metadata
        end

    *Yves Senn*

37 38 39 40
*   Revert 408227d9c5ed7d, 'quote numeric'. This introduced some regressions.

    *Steve Klabnik*

41
*   Fix calculation of `db_runtime` property in
42
   `ActiveRecord::Railties::ControllerRuntime#cleanup_view_runtime`.
43
    Previously, after raising `ActionView::MissingTemplate`, `db_runtime` was
44 45 46 47 48
    not populated.
    Fixes #9215.

    *Igor Fedoronchuk*

49 50 51 52 53
*   Do not try to touch invalid (and thus not persisted) parent record
    for a `belongs_to :parent, touch: true` association

    *Olek Janiszewski*

54 55 56 57 58 59 60 61 62
*   Fix when performing an ordered join query. The bug only
    affected queries where the order was given with a symbol.
    Fixes #9275.

    Example:

        # This will expand the order :name to "authors".name.
        Author.joins(:books).where('books.published = 1').order(:name)

R
Rafael Mendonça França 已提交
63 64 65

## Rails 4.0.0.beta1 (February 25, 2013) ##

66
*   Fix overriding of attributes by `default_scope` on `ActiveRecord::Base#dup`.
R
Rafael Mendonça França 已提交
67 68 69 70 71 72 73

    *Hiroshige UMINO*

*   Update queries now use prepared statements.

    *Olli Rissanen*

74 75 76
*   Fixing issue #8345. Now throwing an error when one attempts to touch a
    new object that has not yet been persisted. For instance:

77 78 79 80
    Example:

        ball = Ball.new
        ball.touch :updated_at   # => raises error
81 82 83 84 85 86

    It is not until the ball object has been persisted that it can be touched.
    This follows the behavior of update_column.

    *John Wang*

87 88
*   Preloading ordered `has_many :through` associations no longer applies
    invalid ordering to the `:through` association.
89 90 91 92
    Fixes #8663.

    *Yves Senn*

93 94 95 96 97 98 99 100 101
*   The auto explain feature has been removed. This feature was
    activated by configuring `config.active_record.auto_explain_threshold_in_seconds`.
    The configuration option was deprecated and has no more effect.

    You can still use `ActiveRecord::Relation#explain` to see the EXPLAIN output for
    any given relation.

    *Yves Senn*

102 103 104 105 106 107
*   The `:on` option for `after_commit` and `after_rollback` now
    accepts an Array of actions.
    Fixes #988.

    Example:

108 109 110
        after_commit :update_cache on: [:create, :update]

    *Yves Senn*
111

112 113 114 115 116
*   Rename related indexes on `rename_table` and `rename_column`. This
    does not affect indexes with custom names.

    *Yves Senn*

117 118 119 120
*   Prevent the creation of indices with too long names, which cause
    internal operations to fail (sqlite3 adapter only). The method
    `allowed_index_name_length` defines the length limit enforced by
    rails. It's value defaults to `index_name_length` but can vary per adapter.
Y
Yves Senn 已提交
121
    Fixes #8264.
122 123 124

    *Yves Senn*

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
*   Fixing issue #776.

    Memory bloat in transactions is handled by having the transaction hold only
    the AR objects which it absolutely needs to know about. These are the AR
    objects with callbacks (they need to be updated as soon as something in the
    transaction occurs).

    All other AR objects can be updated lazily by keeping a reference to a
    TransactionState object. If an AR object gets inside a transaction, then
    the transaction will add its TransactionState to the AR object. When the
    user makes a call to some attribute on an AR object (which has no
    callbacks) associated with a transaction, the AR object will call the
    sync_with_transaction_state method and make sure it is up to date with the
    transaction. After it has synced with the transaction state, the AR object
    will return the attribute that was requested.

    Most of the logic in the changes are used to handle multiple transactions,
    in which case the AR object has to recursively follow parent pointers of
    TransactionState objects.

    *John Wang*

147
*   Descriptive error message when the necessary AR adapter gem was not found.
Y
Yves Senn 已提交
148
    Fixes #7313.
149 150 151

    *Yves Senn*

152
*   Active Record now raises an error when blank arguments are passed to query
153
    methods for which blank arguments do not make sense.
154 155 156

    Example:

157
        Post.includes()     # => raises error
158

159 160
    *John Wang*

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
*   Simplified type casting code for timezone aware attributes to use the
    `in_time_zone` method if it is available. This introduces a subtle change
    of behavior when using `Date` instances as they are directly converted to
    `ActiveSupport::TimeWithZone` instances without first being converted to
    `Time` instances. For example:

        # Rails 3.2 behavior
        >> Date.today.to_time.in_time_zone
        => Wed, 13 Feb 2013 07:00:00 UTC +00:00

        # Rails 4.0 behavior
        >> Date.today.in_time_zone
        => Wed, 13 Feb 2013 00:00:00 UTC +00:00

    On the plus side it now behaves the same whether you pass a `String` date
    or an actual `Date` instance. For example:

        # Rails 3.2 behavior
        >> Date.civil(2013, 2, 13).to_time.in_time_zone
        => Wed, 13 Feb 2013 07:00:00 UTC +00:00
        >> Time.zone.parse("2013-02-13")
        => Wed, 13 Feb 2013 00:00:00 UTC +00:00

        # Rails 4.0 behavior
        >> Date.civil(2013, 2, 13).in_time_zone
        => Wed, 13 Feb 2013 00:00:00 UTC +00:00
        >> "2013-02-13".in_time_zone
        => Wed, 13 Feb 2013 00:00:00 UTC +00:00

    If you need the old behavior you can convert the dates to times manually.
    For example:

        >> Post.new(created_at: Date.today).created_at
        => Wed, 13 Feb 2013 00:00:00 UTC +00:00

        >> Post.new(created_at: Date.today.to_time).created_at
        => Wed, 13 Feb 2013 07:00:00 UTC +00:00

    *Andrew White*

201 202 203 204 205 206 207 208 209 210 211 212 213 214
*   Preloading `has_many :through` associations with conditions won't
    cache the `:through` association. This will prevent invalid
    subsets to be cached.
    Fixes #8423.

    Example:

        class User
          has_many :posts
          has_many :recent_comments, -> { where('created_at > ?', 1.week.ago) }, :through => :posts
        end

        a_user = User.includes(:recent_comments).first

X
Xavier Noria 已提交
215
        # This is preloaded.
216 217
        a_user.recent_comments

X
Xavier Noria 已提交
218
        # This is not preloaded, fetched now.
219 220 221 222
        a_user.posts

    *Yves Senn*

X
Xavier Noria 已提交
223
*   Don't run `after_commit` callbacks when creating through an association
224 225
    if saving the record fails.

X
Xavier Noria 已提交
226
    *James Miller*
227

228 229 230 231 232 233 234 235 236 237 238 239
*   Allow store accessors to be overrided like other attribute methods, e.g.:

        class User < ActiveRecord::Base
          store :settings, accessors: [ :color, :homepage ], coder: JSON

          def color
            super || 'red'
          end
        end

    *Sergey Nartimov*

240 241 242 243 244 245 246 247 248 249
*   Quote numeric values being compared to non-numeric columns. Otherwise,
    in some database, the string column values will be coerced to a numeric
    allowing 0, 0.0 or false to match any string starting with a non-digit.

    Example:

        App.where(apikey: 0) # => SELECT * FROM users WHERE apikey = '0'

    *Dylan Smith*

250 251 252 253 254
*   Schema dumper supports dumping the enabled database extensions to `schema.rb`
    (currently only supported by postgresql).

    *Justin George*

255 256
*   The database adpters now converts the options passed thought `DATABASE_URL`
    environment variable to the proper Ruby types before using. For example, SQLite requires
257 258 259 260 261 262 263 264
    that the timeout value is an integer, and PostgreSQL requires that the
    prepared_statements option is a boolean. These now work as expected:

    Example:

        DATABASE_URL=sqlite3://localhost/test_db?timeout=500
        DATABASE_URL=postgresql://localhost/test_db?prepared_statements=false

265
    *Aaron Stone + Rafael Mendonça França*
266

R
Rafael Mendonça França 已提交
267
*   `Relation#merge` now only overwrites where values on the LHS of the
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    merge. Consider:

        left  = Person.where(age: [13, 14, 15])
        right = Person.where(age: [13, 14]).where(age: [14, 15])

    `left` results in the following SQL:

        WHERE age IN (13, 14, 15)

    `right` results in the following SQL:

        WHERE age IN (13, 14) AND age IN (14, 15)

    Previously, `left.merge(right)` would result in all but the last
    condition being removed:

        WHERE age IN (14, 15)

    Now it results in the LHS condition(s) for `age` being removed, but
    the RHS remains as it is:

        WHERE age IN (13, 14) AND age IN (14, 15)

    *Jon Leighton*

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
*   Fix handling of dirty time zone aware attributes

    Previously, when `time_zone_aware_attributes` were enabled, after
    changing a datetime or timestamp attribute and then changing it back
    to the original value, `changed_attributes` still tracked the
    attribute as changed. This caused `[attribute]_changed?` and
    `changed?` methods to return true incorrectly.

    Example:

        in_time_zone 'Paris' do
          order = Order.new
          original_time = Time.local(2012, 10, 10)
          order.shipped_at = original_time
          order.save
          order.changed? # => false

          # changing value
          order.shipped_at = Time.local(2013, 1, 1)
          order.changed? # => true

          # reverting to original value
          order.shipped_at = original_time
          order.changed? # => false, used to return true
        end

    *Lilibeth De La Cruz*

321
*   When `#count` is used in conjunction with `#uniq` we perform `count(:distinct => true)`.
Y
Yves Senn 已提交
322
    Fixes #6865.
323 324 325

    Example:

R
Rafael Mendonça França 已提交
326
        relation.uniq.count # => SELECT COUNT(DISTINCT *)
327 328 329

    *Yves Senn + Kaspar Schiess*

B
bUg 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
*   PostgreSQL ranges type support. Includes: int4range, int8range,
    numrange, tsrange, tstzrange, daterange

    Ranges can be created with inclusive and exclusive bounds.

    Example:

        create_table :Room do |t|
          t.daterange :availability
        end

        Room.create(availability: (Date.today..Float::INFINITY))
        Room.first.availability # => Wed, 19 Sep 2012..Infinity

    One thing to note: Range class does not support exclusive lower
    bound.

    *Alexander Grebennik*

W
wangjohn 已提交
349 350 351 352 353
*   Added a state instance variable to each transaction. Will allow other objects
    to know whether a transaction has been committed or rolled back.

    *John Wang*

354
*   Collection associations `#empty?` always respects builded records.
Y
Yves Senn 已提交
355
    Fixes #8879.
356 357 358 359 360 361 362 363 364

    Example:

        widget = Widget.new
        widget.things.build
        widget.things.empty? # => false

    *Yves Senn*

365
*   Support for PostgreSQL's `ltree` data type.
366 367 368

    *Rob Worley*

369
*   Fix undefined method `to_i` when calling `new` on a scope that uses an
370 371
    Array; Fix FloatDomainError when setting integer column to NaN.
    Fixes #8718, #8734, #8757.
372

373
    *Jason Stirk + Tristan Harward*
374 375

*   Rename `update_attributes` to `update`, keep `update_attributes` as an alias for `update` method.
376 377 378
    This is a soft-deprecation for `update_attributes`, although it will still work without any
    deprecation message in 4.0 is recommended to start using `update` since `update_attributes` will be
    deprecated and removed in future versions of Rails.
379

380
    *Amparo Luna + Guillermo Iguaran*
381

382
*   `after_commit` and `after_rollback` now validate the `:on` option and raise an `ArgumentError`
383
    if it is not one of `:create`, `:destroy` or `:update`
384 385 386

    *Pascal Friederich*

387 388 389
*   Improve ways to write `change` migrations, making the old `up` & `down` methods no longer necessary.

    * The methods `drop_table` and `remove_column` are now reversible, as long as the necessary information is given.
X
Xavier Noria 已提交
390
      The method `remove_column` used to accept multiple column names; instead use `remove_columns` (which is not reversible).
391 392 393 394 395 396 397 398 399
      The method `change_table` is also reversible, as long as its block doesn't call `remove`, `change` or `change_default`

    * New method `reversible` makes it possible to specify code to be run when migrating up or down.
      See the [Guide on Migration](https://github.com/rails/rails/blob/master/guides/source/migrations.md#using-the-reversible-method)

    * New method `revert` will revert a whole migration or the given block.
      If migrating down, the given migration / block is run normally.
      See the [Guide on Migration](https://github.com/rails/rails/blob/master/guides/source/migrations.md#reverting-previous-migrations)

400 401
    Attempting to revert the methods `execute`, `remove_columns` and `change_column` will now
    raise an `IrreversibleMigration` instead of actually executing them without any output.
402 403 404

    *Marc-André Lafortune*

405 406 407 408 409
*   Serialized attributes can be serialized in integer columns.
    Fix #8575.

    *Rafael Mendonça França*

410
*   Keep index names when using `alter_table` with sqlite3.
411
    Fix #3489.
412 413 414

    *Yves Senn*

415
*   Add ability for postgresql adapter to disable user triggers in `disable_referential_integrity`.
416
    Fix #5523.
417 418 419

    *Gary S. Weaver*

420 421 422 423 424
*   Added support for `validates_uniqueness_of` in PostgreSQL array columns.
    Fixes #8075.

    *Pedro Padron*

425 426 427 428
*   Allow int4range and int8range columns to be created in PostgreSQL and properly convert to/from database.

    *Alexey Vasiliev aka leopard*

429 430 431 432
*   Do not log the binding values for binary columns.

    *Matthew M. Boedicker*

433 434 435 436 437
*   Fix counter cache columns not updated when replacing `has_many :through`
    associations.

    *Matthew Robertson*

438 439 440 441 442
*   Recognize migrations placed in directories containing numbers and 'rb'.
    Fix #8492

    *Yves Senn*

443
*   Add `ActiveRecord::Base.cache_timestamp_format` class attribute to control
444
    the format of the timestamp value in the cache key. Defaults to `:nsec`.
445 446 447 448
    Fixes #8195.

    *Rafael Mendonça França*

449
*   Session variables can be set for the `mysql`, `mysql2`, and `postgresql` adapters
450
    in the `variables: <hash>` parameter in `config/database.yml`. The key-value pairs of this
451 452 453 454 455 456
    hash will be sent in a `SET key = value` query on new database connections. See also:
    http://dev.mysql.com/doc/refman/5.0/en/set-statement.html
    http://www.postgresql.org/docs/8.3/static/sql-set.html

    *Aaron Stone*

457
*   Allow `Relation#where` with no arguments to be chained with new `not` query method.
458 459 460

    Example:

461
        Developer.where.not(name: 'Aaron')
462 463 464

    *Akira Matsuda*

465 466 467 468 469 470 471 472
*   Unscope `update_column(s)` query to ignore default scope.

    When applying `default_scope` to a class with a where clause, using
    `update_column(s)` could generate a query that would not properly update
    the record due to the where clause from the `default_scope` being applied
    to the update query.

        class User < ActiveRecord::Base
473
          default_scope -> { where(active: true) }
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
        end

        user = User.first
        user.active = false
        user.save!

        user.update_column(:active, true) # => false

    In this situation we want to skip the default_scope clause and just
    update the record based on the primary key. With this change:

        user.update_column(:active, true) # => true

    Fixes #8436.

    *Carlos Antonio da Silva*

C
Carlos Antonio da Silva 已提交
491 492
*   SQLite adapter no longer corrupts binary data if the data contains `%00`.

S
Steve Klabnik 已提交
493 494
    *Chris Feist*

C
Carlos Antonio da Silva 已提交
495 496
*   Fix performance problem with `primary_key` method in PostgreSQL adapter when having many schemas.
    Uses `pg_constraint` table instead of `pg_depend` table which has many records in general.
497 498 499 500
    Fix #8414

    *kennyj*

501 502 503 504 505 506
*   Do not instantiate intermediate Active Record objects when eager loading.
    These records caused `after_find` to run more than expected.
    Fix #3313

    *Yves Senn*

507
*   Add STI support to init and building associations.
508 509
    Allows you to do `BaseClass.new(type: "SubClass")` as well as
    `parent.children.build(type: "SubClass")` or `parent.build_child`
510 511 512 513 514 515
    to initialize an STI subclass. Ensures that the class name is a
    valid class and that it is in the ancestors of the super class
    that the association is expecting.

    *Jason Rush*

516 517 518 519
*   Observers was extracted from Active Record as `rails-observers` gem.

    *Rafael Mendonça França*

520 521
*   Ensure that associations take a symbol argument. *Steve Klabnik*

522
*   Fix dirty attribute checks for `TimeZoneConversion` with nil and blank
523 524 525 526 527
    datetime attributes. Setting a nil datetime to a blank string should not
    result in a change being flagged. Fix #8310

    *Alisdair McDiarmid*

528 529 530 531 532
*   Prevent mass assignment to the type column of polymorphic associations when using `build`
    Fix #8265

    *Yves Senn*

533 534 535 536 537
*   Deprecate calling `Relation#sum` with a block. To perform a calculation over
    the array result of the relation, use `to_a.sum(&block)`.

    *Carlos Antonio da Silva*

538 539
*   Fix postgresql adapter to handle BC timestamps correctly

540
        HistoryEvent.create!(name: "something", occured_at: Date.new(0) - 5.years)
541 542 543

    *Bogdan Gusiev*

544 545 546 547 548
*   When running migrations on Postgresql, the `:limit` option for `binary` and `text` columns is silently dropped.
    Previously, these migrations caused sql exceptions, because Postgresql doesn't support limits on these types.

    *Victor Costan*

549 550
*   Don't change STI type when calling `ActiveRecord::Base#becomes`.
    Add `ActiveRecord::Base#becomes!` with the previous behavior.
551

552
    See #3023 for more information.
553 554 555

    *Thomas Hollstegge*

J
Jarek Radosz 已提交
556 557 558 559 560 561 562 563
*   `rename_index` can be used inside a `change_table` block.

        change_table :accounts do |t|
          t.rename_index :user_id, :account_id
        end

    *Jarek Radosz*

564
*   `#pluck` can be used on a relation with `select` clause. Fix #7551
565

566
    Example:
567 568 569

        Topic.select([:approved, :id]).order(:id).pluck(:id)

570
    *Yves Senn*
571

572
*   Do not create useless database transaction when building `has_one` association.
573

574 575 576 577 578 579 580
    Example:

        User.has_one :profile
        User.new.build_profile

    *Bogdan Gusiev*

581
*   `:counter_cache` option for `has_many` associations to support custom named counter caches.
582 583 584 585
    Fix #7993

    *Yves Senn*

586 587 588 589 590 591 592
*   Deprecate the possibility to pass a string as third argument of `add_index`.
    Pass `unique: true` instead.

        add_index(:users, :organization_id, unique: true)

    *Rafael Mendonça França*

593 594 595 596
*   Raise an `ArgumentError` when passing an invalid option to `add_index`.

    *Rafael Mendonça França*

597 598 599 600
*   Fix `find_in_batches` crashing when IDs are strings and start option is not specified.

    *Alexis Bernard*

601 602 603 604
*   `AR::Base#attributes_before_type_cast` now returns unserialized values for serialized attributes.

    *Nikita Afanasenko*

605
*   Use query cache/uncache when using `DATABASE_URL`.
606 607 608 609
    Fix #6951.

    *kennyj*

610 611 612 613
*   Fix bug where `update_columns` and `update_column` would not let you update the primary key column.

    *Henrik Nyh*

614 615 616 617 618
*   The `create_table` method raises an `ArgumentError` when the primary key column is redefined.
    Fix #6378

    *Yves Senn*

619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
*   `ActiveRecord::AttributeMethods#[]` raises `ActiveModel::MissingAttributeError`
    error if the given attribute is missing. Fixes #5433.

        class Person < ActiveRecord::Base
          belongs_to :company
        end

        # Before:
        person = Person.select('id').first
        person[:name]       # => nil
        person.name         # => ActiveModel::MissingAttributeError: missing_attribute: name
        person[:company_id] # => nil
        person.company      # => nil

        # After:
        person = Person.select('id').first
        person[:name]       # => ActiveModel::MissingAttributeError: missing_attribute: name
        person.name         # => ActiveModel::MissingAttributeError: missing_attribute: name
        person[:company_id] # => ActiveModel::MissingAttributeError: missing_attribute: company_id
        person.company      # => ActiveModel::MissingAttributeError: missing_attribute: company_id

    *Francesco Rodriguez*

642 643 644 645
*   Small binary fields use the `VARBINARY` MySQL type, instead of `TINYBLOB`.

    *Victor Costan*

646 647 648 649
*   Decode URI encoded attributes on database connection URLs.

    *Shawn Veader*

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
*   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.

674 675 676 677 678 679 680 681 682 683 684
    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.
685 686 687

    *Jon Leighton*

688
*   Fix bug with presence validation of associations. Would incorrectly add duplicated errors
689 690 691 692
    when the association was blank. Bug introduced in 1fab518c6a75dac5773654646eb724a59741bc13.

    *Scott Willson*

693
*   Fix bug where sum(expression) returns string '0' for no matching records.
694 695 696 697
    Fixes #7439

    *Tim Macfarlane*

698 699 700 701
*   PostgreSQL adapter correctly fetches default values when using multiple schemas and domains in a db. Fixes #7914

    *Arturo Pie*

702 703 704 705
*   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
706

707 708 709 710 711
        User.order(:name, email: :desc)
        # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC

    *Tima Maslyuchenko*

712 713 714 715 716 717 718 719 720 721 722 723
*   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*

724 725 726 727 728
*   The postgres adapter now supports tables with capital letters.
    Fix #5920

    *Yves Senn*

729 730
*   `CollectionAssociation#count` returns `0` without querying if the
    parent record is not persisted.
731 732 733

    Before:

734
        person.pets.count
735 736 737 738 739
        # SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" IS NULL
        # => 0

    After:

740
        person.pets.count
741 742 743 744 745
        # fires without sql query
        # => 0

    *Francesco Rodriguez*

746 747 748 749 750
*   Fix `reset_counters` crashing on `has_many :through` associations.
    Fix #7822.

    *lulalala*

J
Jon Leighton 已提交
751 752 753 754 755 756 757 758 759 760 761
*   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).

762 763 764 765
    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 已提交
766 767
    *Jon Leighton*

768 769 770 771
*   Allow before and after validations to take an array of lifecycle events

    *John Foley*

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 801 802 803 804 805 806
*   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*

807 808 809 810 811 812 813 814 815 816
*   `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
817
    used it (ex. `AR::Base.new`, `AR::Base.create`, `AR::Base#update_attributes`, etc).
818 819 820

    *Guillermo Iguaran*

821 822 823 824 825 826 827 828 829 830 831
*   Fix the return of querying with an empty hash.
    Fix #6971.

        User.where(token: {})

    Before:

        #=> SELECT * FROM users;

    After:

832
        #=> SELECT * FROM users WHERE 1=0;
833 834

    *Damien Mathieu*
D
Damien Mathieu 已提交
835

836 837 838
*   Fix creation of through association models when using `collection=[]`
    on a `has_many :through` association from an unsaved model.
    Fix #7661.
839 840 841

    *Ernie Miller*

K
kennyj 已提交
842
*   Explain only normal CRUD sql (select / update / insert / delete).
843 844
    Fix problem that explains unexplainable sql.
    Closes #7544 #6458.
K
kennyj 已提交
845 846 847

    *kennyj*

M
Matt Jones 已提交
848 849 850 851 852 853
*   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*

854
*   Accept `belongs_to` (including polymorphic) association keys in queries.
855 856 857

    The following queries are now equivalent:

858 859
        Post.where(author: author)
        Post.where(author_id: author)
860

861 862
        PriceEstimate.where(estimate_of: treasure)
        PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
863 864 865

    *Peter Brown*

866 867 868 869 870
*   Use native `mysqldump` command instead of `structure_dump` method
    when dumping the database structure to a sql file. Fixes #5547.

    *kennyj*

871
*   PostgreSQL inet and cidr types are converted to `IPAddr` objects.
872

873 874 875 876 877 878 879 880
    *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|
881
          t.integer :int_array, array: true
882
          # integer[]
883
          t.integer :int_array, array: true, length: 2
884
          # smallint[]
885
          t.string :string_array, array: true, length: 30
886
          # char varying(30)[]
887
        end
888

889
    This respects any other migration detail (limits, defaults, etc).
X
Xavier Noria 已提交
890
    Active Record will serialize and deserialize the array columns on
891 892 893 894 895 896 897 898
    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
899
    parsing PostgreSQL's array representation.
900 901 902

    *Dan McClain*

903 904
*   Attribute predicate methods, such as `article.title?`, will now raise
    `ActiveModel::MissingAttributeError` if the attribute being queried for
905
    truthiness was not read from the database, instead of just returning `false`.
906 907 908

    *Ernie Miller*

909 910 911 912
*   `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*
913

914 915 916
*   Map interval with precision to string datatype in PostgreSQL. Fixes #7518.

    *Yves Senn*
917

918 919 920
*   Fix eagerly loading associations without primary keys. Fixes #4976.

    *Kelley Reynolds*
921

922 923 924 925 926 927
*   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 已提交
928
*   Fix bug when calling `store_accessor` multiple times.
929 930 931 932 933 934 935 936 937
    Fixes #7532.

    *Matt Jones*

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

    *Matt Jones*

938 939 940 941
*   Fix `ActiveRecord::Relation#pluck` when columns or tables are reserved words.

    *Ian Lesperance*

942
*   Allow JSON columns to be created in PostgreSQL and properly encoded/decoded.
943 944 945 946
    to/from database.

    *Dickson S. Guedes*

947
*   Fix time column type casting for invalid time string values to correctly return `nil`.
948 949 950

    *Adam Meehan*

951
*   Allow to pass Symbol or Proc into `:limit` option of #accepts_nested_attributes_for.
M
Mikhail Dieterle 已提交
952 953 954

    *Mikhail Dieterle*

955
*   ActiveRecord::SessionStore has been extracted from Active Record as `activerecord-session_store`
956 957 958
    gem. Please read the `README.md` file on the gem for the usage.

    *Prem Sichanugrist*
959

960 961 962 963 964 965
*   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*

966 967 968 969
*   `serialized_attributes` and `_attr_readonly` become class method only. Instance reader methods are deprecated.

    *kennyj*

970 971 972 973 974
*   Round usec when comparing timestamp attributes in the dirty tracking.
    Fixes #6975.

    *kennyj*

975
*   Use inversed parent for first and last child of `has_many` association.
976 977 978

    *Ravil Bayramgalin*

979
*   Fix `Column.microseconds` and `Column.fast_string_to_time` to avoid converting
980 981 982 983 984
    timestamp seconds to a float, since it occasionally results in inaccuracies
    with microsecond-precision times. Fixes #7352.

    *Ari Pollak*

985 986 987
*   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.

988
    *Christian Seiler*
989

990 991 992 993
*   Raise `ArgumentError` if list of attributes to change is empty in `update_all`.

    *Roman Shatsov*

994 995 996 997 998
*   Fix AR#create to return an unsaved record when AR::RecordInvalid is
    raised. Fixes #3217.

    *Dave Yeu*

999 1000
*   Fixed table name prefix that is generated in engines for namespaced models.

1001 1002
    *Wojciech Wnętrzak*

1003
*   Make sure `:environment` task is executed before `db:schema:load` or `db:structure:load`.
R
Rafael Mendonça França 已提交
1004 1005 1006 1007
    Fixes #4772.

    *Seamus Abshere*

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
*   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*

1028
*   Add CollectionProxy#scope.
J
Jon Leighton 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

    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*

1046
*   Add `Relation#load`.
J
Jon Leighton 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

    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*

1061 1062 1063 1064 1065 1066 1067 1068 1069
*   `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*

1070
*   `Model.all` now returns an `ActiveRecord::Relation`, rather than an
1071
    array of records. Use `Relation#to_a` if you really want an array.
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

    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*

1088 1089 1090 1091 1092 1093 1094
*   `: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
1095
    :through`.
1096 1097 1098

    *Jon Leighton*

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
*   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*

1110 1111 1112
*   The migration generator now creates a join table with (commented) indexes every time
    the migration name contains the word `join_table`:

1113
        rails g migration create_join_table_for_artists_and_musics artist_id:index music_id
1114 1115 1116

    *Aleksey Magusev*

1117 1118
*   Add `add_reference` and `remove_reference` schema statements. Aliases, `add_belongs_to`
    and `remove_belongs_to` are acceptable. References are reversible.
1119

1120
    Examples:
1121 1122 1123

        # Create a user_id column
        add_reference(:products, :user)
1124
        # Create a supplier_id, supplier_type columns and appropriate index
1125 1126 1127 1128 1129 1130
        add_reference(:products, :supplier, polymorphic: true, index: true)
        # Remove polymorphic reference
        remove_reference(:products, :supplier, polymorphic: true)

    *Aleksey Magusev*

1131 1132 1133 1134 1135 1136 1137
*   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*

1138 1139
*   `ActiveRecord::Relation#inspect` now makes it clear that you are
    dealing with a `Relation` object rather than an array:.
1140

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

1144
        User.where(age: 30).to_a.inspect
1145
        # => [#<User ...>, #<User ...>]
1146

1147 1148 1149
    The number of records displayed will be limited to 10.

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

1151
*   Add `collation` and `ctype` support to PostgreSQL. These are available for PostgreSQL 8.4 or later.
1152 1153
    Example:

1154 1155 1156 1157 1158 1159 1160 1161 1162
        development:
          adapter: postgresql
          host: localhost
          database: rails_development
          username: foo
          password: bar
          encoding: UTF8
          collation: ja_JP.UTF8
          ctype: ja_JP.UTF8
1163 1164 1165

    *kennyj*

1166
*   Changed `validates_presence_of` on an association so that children objects
1167 1168 1169 1170 1171 1172
    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 已提交
1173 1174 1175 1176
*   `FinderMethods#exists?` now returns `false` with the `false` argument.

    *Egor Lynko*

1177 1178 1179 1180 1181 1182
*   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|
1183
            t.timestamps precision: 0
1184 1185 1186 1187 1188
          end
        end

    *Tony Schneider*

1189
*   Allow `ActiveRecord::Relation#pluck` to accept multiple columns. Returns an
1190
    array of arrays containing the typecasted values:
1191 1192 1193 1194 1195 1196 1197

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

    *Jeroen van Ingen & Carlos Antonio da Silva*

1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
*   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*

1230
*   Move HABTM validity checks to `ActiveRecord::Reflection`. One side effect of
1231 1232 1233 1234 1235 1236
    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*

1237
*   Added `stored_attributes` hash which contains the attributes stored using
1238
    `ActiveRecord::Store`. This allows you to retrieve the list of attributes
1239
    you've defined.
1240

1241 1242 1243 1244 1245 1246 1247
       class User < ActiveRecord::Base
         store :settings, accessors: [:color, :homepage]
       end

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

    *Joost Baaij & Carlos Antonio da Silva*
1248

1249 1250 1251 1252 1253 1254
*   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*

1255 1256 1257
*   Add uuid datatype support to PostgreSQL adapter.

    *Konstantin Shabanov*
1258

1259
*   Added `ActiveRecord::Migration.check_pending!` that raises an error if
1260 1261 1262
    migrations are pending.

    *Richard Schneeman*
1263

1264 1265 1266 1267 1268
*   Added `#destroy!` which acts like `#destroy` but will raise an
    `ActiveRecord::RecordNotDestroyed` exception instead of returning `false`.

    *Marc-André Lafortune*

1269 1270 1271 1272 1273 1274 1275 1276 1277
*   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>]
1278
        person.pets.delete(2, 3) # => [#<Pet id: 2>, #<Pet id: 3>]
1279 1280 1281

    *Francesco Rodriguez*

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
*   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
1292
        `find_or_create_by(...)` or where(...).first_or_create`
1293
      * `find_or_create_by_...!` can be rewritten using
1294
        `find_or_create_by!(...) or `where(...).first_or_create!`
1295 1296

    The implementation of the deprecated dynamic finders has been moved
1297
    to the `activerecord-deprecated_finders` gem. See below for details.
1298 1299 1300 1301 1302 1303 1304

    *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:

1305
        Post.find(:all, conditions: { comments_count: 10 }, limit: 5)
1306 1307 1308 1309 1310 1311 1312

    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:

1313
        Post.all.merge(where: { comments_count: 10 }, limit: 5)
1314 1315 1316 1317

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

1318
    `Relation#merge` now accepts a hash of
1319 1320 1321 1322
    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:

1323 1324
      * `:conditions` becomes `:where`.
      * `:include` becomes `:includes`.
1325

1326
    The code to implement the deprecated features has been moved out to the
X
typo  
Xavier Noria 已提交
1327
    `activerecord-deprecated_finders` gem. This gem is a dependency of Active
1328 1329 1330
    Record in Rails 4.0, so the interface works out of the box. It will no
    longer be a dependency from Rails 4.1 (you'll need to add it to the
    `Gemfile` in 4.1), and will be maintained until Rails 5.0.
1331 1332 1333

    *Jon Leighton*

J
Johannes Barre 已提交
1334 1335 1336 1337
*   It's not possible anymore to destroy a model marked as read only.

    *Johannes Barre*

1338
*   Added ability to ActiveRecord::Relation#from to accept other ActiveRecord::Relation objects.
1339 1340 1341 1342 1343 1344

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

    *Radoslav Stankov*

1345 1346 1347 1348 1349 1350
*   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*
1351

1352 1353 1354 1355 1356 1357
*   `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*

1358
*   Added default order to `first` to assure consistent results among
1359
    different database engines. Introduced `take` as a replacement to
1360 1361 1362 1363
    the old behavior of `first`.

    *Marcelo Silveira*

1364
*   Added an `:index` option to automatically create indexes for references
1365 1366 1367 1368 1369 1370 1371
    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|
1372
        t.references :person, index: true
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
      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.

1384
    *Joshua Wood*
1385

1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
*   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 已提交
1396 1397 1398 1399 1400
*   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 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
*   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*

1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
*   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 已提交
1442

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
*   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

1454
      2) add config.active_record.use_schema_cache_dump = true in config/production.rb. BTW, true is default.
1455 1456 1457

      3) boot rails.
      RAILS_ENV=production bundle exec rails server
1458
      => use db/schema_cache.dump
1459 1460 1461 1462 1463 1464 1465

      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*

1466
*   Added support for partial indices to PostgreSQL adapter.
1467 1468 1469 1470

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

1471
        add_index(:accounts, :code, where: 'active')
1472

1473
        Generates
1474

1475
        CREATE INDEX index_accounts_on_code ON accounts(code) WHERE active
1476 1477 1478

    *Marcelo Silveira*

1479
*   Implemented ActiveRecord::Relation#none method.
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489

    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
1490
    object pattern for the Relation class.
1491

1492 1493 1494
    *Juanjo Bazán*

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

1497 1498
    The `:restrict` option is renamed to `:restrict_with_exception` to
    make this distinction explicit.
1499

1500
    *Manoj Kumar & Jon Leighton*
1501

1502
*   Added `create_join_table` migration helper to create HABTM join tables.
1503 1504 1505

        create_join_table :products, :categories
        # =>
1506 1507 1508
        # create_table :categories_products, id: false do |td|
        #   td.integer :product_id,  null: false
        #   td.integer :category_id, null: false
1509 1510 1511 1512
        # end

    *Rafael Mendonça França*

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

1516 1517
    *Aaron Paterson*

1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
*   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.

1528 1529 1530 1531
    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:
1532 1533 1534 1535 1536 1537 1538 1539

        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:

1540 1541 1542
        Post.includes(:comments).where(comments: { name: 'foo' })
        Post.includes(:comments).where('comments.name' => 'foo')
        Post.includes(:comments).order('comments.name')
1543

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

1548
    *Jon Leighton*
1549

1550
*   Support for the `schema_info` table has been dropped. Please
1551 1552
    switch to `schema_migrations`.

1553 1554 1555
    *Aaron Patterson*

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

1558 1559
    *Aaron Patterson*

1560 1561
*   PostgreSQL hstore records can be created.

1562 1563
    *Aaron Patterson*

1564 1565
*   PostgreSQL hstore types are automatically deserialized from the database.

1566 1567
    *Aaron Patterson*

1568

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