Commit Graph

419 Commits

Author SHA1 Message Date
Yves Senn
ede2343031 fix regression when loading fixture files with symbol keys.
Closes #22584.
2016-01-13 10:11:54 +01:00
Ryuta Kamizono
a093afd8ce Fix test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct to NULL-agnostic way
The sort order of NULL depends on the RDBS implementation. This commit
is to fix the test to NULL-agnostic way.

Example:

    ```
    activerecord_unittest=# SELECT  DISTINCT "posts"."id", author_addresses_authors.id AS alias_0 FROM "posts" LEFT OUTER JOIN "authors" ON "authors"."id" = "posts"."author_id" LEFT OUTER JOIN "author_addresses" ON "author_addresses"."id" = "authors"."author_address_id" LEFT OUTER JOIN "categorizations" ON "categorizations"."category_id" = "posts"."id" LEFT OUTER JOIN "authors" "authors_posts" ON "authors_posts"."id" = "categorizations"."author_id" LEFT OUTER JOIN "author_addresses" "author_addresses_authors" ON "author_addresses_authors"."id" = "authors_posts"."author_address_id" ORDER BY author_addresses_authors.id DESC;
     id | alias_0
    ----+---------
      1 |
      2 |
      3 |
      4 |
      5 |
      6 |
      7 |
      8 |
      9 |
     10 |
     11 |
      1 |       1
    (12 rows)
    ```

    ```
    root@localhost [activerecord_unittest] > SELECT  DISTINCT `posts`.`id`, author_addresses_authors.id AS alias_0 FROM `posts` LEFT OUTER JOIN `authors` ON `authors`.`id` = `posts`.`author_id` LEFT OUTER JOIN `author_addresses` ON `author_addresses`.`id` = `authors`.`author_address_id` LEFT OUTER JOIN `categorizations` ON `categorizations`.`category_id` = `posts`.`id` LEFT OUTER JOIN `authors` `authors_posts` ON `authors_posts`.`id` = `categorizations`.`author_id` LEFT OUTER JOIN `author_addresses` `author_addresses_authors` ON `author_addresses_authors`.`id` = `authors_posts`.`author_address_id` ORDER BY author_addresses_authors.id DESC;
    +----+---------+
    | id | alias_0 |
    +----+---------+
    |  1 |       1 |
    |  3 |    NULL |
    |  1 |    NULL |
    |  2 |    NULL |
    |  4 |    NULL |
    |  5 |    NULL |
    |  6 |    NULL |
    |  7 |    NULL |
    |  8 |    NULL |
    |  9 |    NULL |
    | 10 |    NULL |
    | 11 |    NULL |
    +----+---------+
    12 rows in set (0.00 sec)
    ```
2015-12-19 17:38:42 +09:00
Sean Griffin
f7d0a3ba7e Merge pull request #18548 from sebjacobs/support-bidirectional-destroy-dependencies
Add support for bidirectional destroy dependencies
2015-10-28 12:24:07 -06:00
Yves Senn
591a0bb87f Merge pull request #20574 from repinel/fix-db-fixtures-load
Allow fixtures YAML files to set the model class in the file itself

Conflicts:
	activerecord/CHANGELOG.md
2015-09-30 11:06:41 +02:00
Roque Pinel
2acec46577 Allow fixtures YAML files to set the model class in the file itself
Currently, `set_fixture_class` is only available using the
`TestFixtures` concern and it is ignored for `rake db:fixtures:load`.
Using the correct model class, it is possible for the fixture load
to also load the associations from the YAML files (e.g., `:belongs_to`
and `:has_many`).
2015-09-11 14:29:06 -04:00
Yves Senn
e50fe85180 descriptive error message when fixtures contian a missing column.
Closes #21201.
2015-08-13 17:13:32 +02:00
eileencodes
cc7ef0cf19 Fix spelling of Thoughtleadering
Not much of a thought leader if I can't spell it correctly 😉
2015-07-02 15:48:47 -04:00
eileencodes
eff3a3178e Use default model enum in fixtures if not defined
After 908cfef was introduced fixtures that did not set an enum would
return nil instead of the default enum value.

The fixtures should assume the default if a different enum is not
defined.

The change checks first if the enum is defined in the fixture before
setting it based on the fixture.
2015-07-02 15:42:52 -04:00
David Heinemeier Hansson
5f5e6d9249 Add pending test for the great-grandparent touching bug from #19324 2015-06-25 14:23:06 +02:00
Igor Kapkov
09bef7684a Add enum prefix/suffix option to enum definition
Fixes #17511 and #17415
2015-06-12 12:07:55 +08:00
Victor Costan
2b2f41fd97 Fix crash when loading fixture with belongs_to association defined in abstract base class. 2015-06-04 12:38:00 -04:00
George Claghorn
908cfef6e2 Resolve enums in test fixtures
Currently, values for columns backing Active Record enums must be
specified as integers in test fixtures:

    awdr:
      title: "Agile Web Development with Rails"
      status: 2

    rfr:
      title: "Ruby for Rails"
      status: <%= Book.statuses[:proposed] %>

This is potentially confusing, since enum values are typically
specified as symbols or strings in application code. To resolve the
confusion, this change permits the use of symbols or strings to specify
enum values:

    awdr:
      status: :published

It is compatible with fixtures that specify enum values as integers.
2015-05-27 21:48:58 -04:00
Seb Jacobs
d5bf649a53 Add support for bidirectional destroy dependencies
Prior to this commit if you defined a bidirectional relationship
between two models with destroy dependencies on both sides, a call to
`destroy` would result in an infinite callback loop.

Take the following relationship.

    class Content < ActiveRecord::Base
      has_one :content_position, dependent: :destroy
    end

    class ContentPosition < ActiveRecord::Base
      belongs_to :content, dependent: :destroy
    end

Calling `Content#destroy` or `ContentPosition#destroy` would result in
an infinite callback loop.

This commit changes the behaviour of `ActiveRecord::Callbacks#destroy`
so that it guards against subsequent callbacks.

Thanks to @zetter for demonstrating the issue with failing tests[1].

[1] rails#13609
2015-01-16 11:41:43 +00:00
Vipul A M
4ae59ebee8 Fixes #18492
- Add check for not deleting previously created fixtures, to overcome sti fixtures from multiple files
- Added fixtures and fixtures test to verify the same

- Fixed wrong fixtures duplicating data insertion in same table
2015-01-14 21:36:58 +05:30
Prathamesh Sonpatki
8da936a5d3 Fix lookup of fixtures with non-string label
- Fixtures with non-string labels such as integers should be accessed
   using integer label as key. For eg. pirates(1) or pirates(42).
 - But this results in NotFound error because the label is converted into string before
   looking up into the fixtures hash.
 - After this commit, the label is converted into string only if its a
   symbol.
 - This issue was fount out while adding a test case for
   https://github.com/rails/rails/commit/7b910917.
2015-01-06 17:15:39 +05:30
Akira Matsuda
8e52954349 Unused csv fixture file 2014-12-09 18:54:07 +09:00
Yves Senn
f766abd4cf make it possible to access fixtures excluded by a default_scope.
Prior to this patch you'd end up with an error like:

```
ActiveRecord::RecordNotFound: Couldn't find <Model> with 'id'=<id> [WHERE (<default_scope condition>)]
```
2014-11-21 14:57:25 +01:00
Sammy Larbi
f43f56e16e Ensure HABTM relationships produce valid class names (Fixes #17119) 2014-11-09 11:56:07 -06:00
Cristian Bica
72d1663bc7 Fix query with nested array in Active Record
`User.where(id: [[1,2],3])` was equal to `User.where(id:[1, 2, 3])`
in Rails 4.1.x but because of some refactoring in Arel this stopped
working in 4.2.0. This fixes it in Rails.

[Dan Olson & Cristian Bica]
2014-09-06 23:46:32 +03:00
Yves Senn
8768305f20 fk: use random digest names
The name of the foreign key is not relevant from a users perspective.
Using random names resolves the urge to rename the foreign key when the
respective table or column is renamed.
2014-06-26 22:03:49 +02:00
Sean Griffin
d730e374ca Deprecate automatic counter caches on has_many :through
Reliant on https://github.com/rails/rails/pull/15747 but pulled to a
separate PR to reduce noise. `has_many :through` associations have the
undocumented behavior of automatically detecting counter caches.
However, the way in which it does so is inconsistent with counter caches
everywhere else, and doesn't actually work consistently.

As with normal `has_many` associations, the user should specify the
counter cache on the `belongs_to`, if they'd like it updated.
2014-06-26 07:24:34 -06:00
Sean Griffin
8019ca7a0f Update test data which doesn't reflect expected usage
Topics call `serialize :content`, which means that the values in the
database should be YAML encoded, and we would only expect to receive
YAML strings to `update_column` and `update_columns`.
2014-06-12 15:33:25 -06:00
Godfrey Chan
2d73f5ae2f Fixed serialization for records with an attribute named format.
* * *

This bug can be triggered when serializing record R (the instance) of type C
(the class), provided that the following conditions are met:

1. The name of one or more columns/attributes on C/R matches an existing private
   method on C (e.g. those defined by `Kernel`, such as `format`).

2. The attribute methods have not yet been generated on C.

In this case, the matching private methods will be called by the serialization
code (with no arguments) and their return values will be serialized instead. If
the method requires one or more arguments, it will result in an `ArgumentError`.

This regression is introduced in d1316bb.

* * *

Attribute methods (e.g. `#name` and `#format`, assuming the class has columns
named `name` and `format` in its database table) are lazily defined. Instead of
defining them when a the class is defined (e.g. in the `inherited` hook on
`ActiveRecord::Base`), this operation is deferred until they are first accessed.

The reason behind this is that is defining those methods requires knowing what
columns are defined on the database table, which usually requires a round-trip
to the database. Deferring their definition until the last-possible moment helps
reducing unnessary work, especially in development mode where classes are
redefined and throw away between requests.

Typically, when an attribute is first accessed (e.g. `a_book.format`), it will
fire the `method_missing` hook on the class, which triggers the definition of
the attribute methods. This even works for methods like `format`, because
calling a private method with an explicit receiver will also trigger that hook.

Unfortunately, `read_attribute_for_serialization` is simply an alias to `send`,
which does not respect method visibility. As a result, when serializing a record
with those conflicting attributes, the `method_missing` is not fired, and as a
result the attribute methods are not defined one would expected.

Before d1316bb, this is negated by the fact that calling the `run_callbacks`
method will also trigger a call to `respond_to?`, which is another trigger point
for the class to define its attribute methods. Therefore, when Active Record
tries to run the `after_find` callbacks, it will also define all the attribute
methods thus masking the problem.

* * *

The proper fix for this problem is probably to restrict `read_attribute_for_serialization`
to call public methods only (i.e. alias `read_attribute_for_serialization` to
`public_send` instead of `send`). This however would be quite risky to change
in a patch release and would probably require a full deprecation cycle.

Another approach would be to override `read_attribute_for_serialization` inside
Active Record to force the definition of attribute methods:

   def read_attribute_for_serialization(attribute)
     self.class.define_attribute_methods
     send(attribute)
   end

Unfortunately, this is quite likely going to cause a performance degradation.

This patch therefore restores the behaviour from the 4-0-stable branch by
explicitly forcing the class to define its attribute methods in a similar spot
(when records are initialized). This should not cause any extra roundtrips to
the database because the `@columns` should already be cached on the class.

Fixes #15188.
2014-05-22 14:35:04 -07:00
Rafael Mendonça França
6931bed1b4 Revert "Merge pull request #14544 from jefflai2/named_scope_sti"
This reverts commit 9a1abedcdeecd9464668695d4f9c1d55a2fd9332, reversing
changes made to c72d6c91a7c0c2dc81cc857a1d6db496e84e0065.

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/test/models/comment.rb

This change break integration with activerecord-deprecated_finders so
I'm reverting until we find a way to make it work with this gem.
2014-05-21 12:15:57 -03:00
Rafael Mendonça França
9a1abedcde Merge pull request #14544 from jefflai2/named_scope_sti
Fixes Issue #13466.

Conflicts:
	activerecord/CHANGELOG.md
2014-05-20 21:35:58 -03:00
Jefferson Lai
9c3afdc327 Fixes Issue #13466.
Changed the call to a scope block to be evaluated with instance_eval.
The result is that ScopeRegistry can use the actual class instead of base_class when
caching scopes so queries made by classes with a common ancestor won't leak scopes.
2014-04-23 17:21:45 -07:00
Rafael Mendonça França
54d8c81fef Merge pull request #12016 from roderickvd/uuid_fixes
Auto-generate stable fixture UUIDs on PostgreSQL

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/lib/active_record/fixtures.rb
	activerecord/test/cases/adapters/postgresql/uuid_test.rb
	activesupport/CHANGELOG.md
2014-04-04 12:52:49 -03:00
Eric Steele
f47421f2a0 Extend fixture label replacement to allow string interpolation
Allows fixtures to use their $LABEL as part of a string instead
of limiting use to the entire value.

    mark:
      first_name: $LABEL
      username: $LABEL1973
      email: $LABEL@$LABELmail.com

    users(:mark).first_name # => mark
    users(:mark).username   # => mark1973
    users(:mark).email      # => mark@markmail.com
2014-03-15 22:11:36 -04:00
Godfrey Chan
41554319f8 Fixed STI classes not defining an attribute method if there is a
conflicting private method defined on its ancestors.

The problem is that `method_defined_within?(name, klass, superklass)`
only works correclty when `klass` and `superklass` are both `Class`es.

If both `klass` and `superklass` are both `Class`es, they share the
same inheritance chain, so if a method is defined on `klass` but not
`superklass`, this method must be introduced at some point between
`klass` and `superklass`.

This does not work when `superklass` is a `Module`. A `Module`'s
inheritance chain contains just itself. So if a method is defined on
`klass` but not on `superklass`, the method could still be defined
somewhere upstream, e.g. in `Object`.

This fix works by avoiding calling `method_defined_within?` with a
module while still fufilling the requirement (checking that the
method is defined withing `superclass` but not is not a generated
attribute method).

4d8ee288 is likely an attempted partial fix for this problem. This
unrolls that fix and properly check the `superclass` as intended.

Fixes #11569.
2014-02-23 11:00:55 -08:00
Jason Meller
03855e790d Ensure AR #second, #third, etc. finders work through associations
This commit fixes two regressions introduced in cafe31a078 where
newly created finder methods #second, #third, #forth, and #fifth
caused a NoMethodError error on reload associations and where we
were pulling the wrong element out of cached associations.

Examples:

  some_book.authors.reload.second

  # Before
  # => NoMethodError: undefined method 'first' for nil:NilClass

  # After
  # => #<Author id: 2, name: "Sally Second", ...>

  some_book.first.authors.first
  some_book.first.authors.second

  # Before
  # => #<Author id: 1, name: "Freddy First", ...>
  # => #<Author id: 1, name: "Freddy First", ...>

  # After
  # => #<Author id: 1, name: "Freddy First", ...>
  # => #<Author id: 2, name: "Sally Second", ...>

Fixes #13783.
2014-01-21 19:35:27 -05:00
Jason Meller
cafe31a078 Ensure #second acts like #first AR finder
This commit bring the famous ordinal Array instance methods defined
in ActiveSupport into ActiveRecord as fully-fledged finders.

These finders ensure a default ascending order of the table's primary
key, and utilize the OFFSET SQL verb to locate the user's desired
record. If an offset is defined in the query, calling #second adds
to the offset to get the actual desired record.

Fixes #13743.
2014-01-20 16:58:18 -05:00
Roderick van Domburg
9330631888 Auto-generate stable fixture UUIDs on PostgreSQL.
Fixes: #11524
2014-01-07 19:05:50 +01:00
David Heinemeier Hansson
e94e97ca79 Extend ActiveRecord::Base#cache_key to take an optional list of timestamp attributes of which the highest will be used. 2013-11-02 16:05:19 -07:00
Aaron Patterson
e95bc57208 we should have unique sponsorable ids in the fixtures at least 2013-10-14 15:27:49 -07:00
David Padilla
33efb44898 Fix broken link to Fixtures documentation on guides
and activerecord tests

[ci skip]
2013-08-29 15:44:12 -05:00
Kassio Borges
4700d0279c load fixtures from linked folders 2013-08-05 16:35:49 -03:00
Neeraj Singh
812469943c has_many through obeys order on through association
fixes #10016
2013-04-04 15:45:13 -04:00
David Heinemeier Hansson
9035cfc0df Merge pull request #9141 from adamgamble/issue-9091
belongs_to :touch should touch old record when transitioning.
2013-04-03 09:56:43 -07:00
Ian Young
66679c8ecd Update other counter caches on destroy 2013-03-20 13:43:07 -07:00
Mack Earnhardt
1d6eabb677 Refactor Person/Friendship relationships to be more intuitive
PR #5210 added a Friendship model to illustrate a bug, but in doing so
created a confusing structure because both belongs_to declarations in
Friendship referred to the same side of the join. The new structure
maintains the integrity of the bug test while changing the follower
relationship to be more useful for other testing.
2013-03-17 02:11:19 -04:00
PikachuEXE
7fc339059c + Add test for auto timestamps update of both old & new parent records 2013-03-14 12:45:56 -05:00
Yves Senn
fa18c61153 test case for serialize default values.
Closes #9110
2013-03-07 17:26:35 +01:00
Jon Leighton
c8d889905d Prevent Relation#merge from collapsing wheres on the RHS
This caused a bug with the new associations implementation, because now
association conditions are represented as Arel nodes internally right up
to when the whole thing gets turned to SQL.

In Rails 3.2, association conditions get turned to raw SQL early on,
which prevents Relation#merge from interfering.

The current implementation was buggy when a default_scope existed on the
target model, since we would basically end up doing:

  default_scope.merge(association_scope)

If default_scope contained a where(foo: 'a') and association_scope
contained a where(foo: 'b').where(foo: 'c') then the merger would see
that the same column is representated on both sides of the merge and
collapse the wheres to all but the last: where(foo: 'c')

Now, the RHS of the merge is left alone.

Fixes #8990
2013-01-27 20:34:52 +00:00
Alexey Muranov
a94220b66c Rename "Fixtures" class to "FixtureSet"
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.
2012-10-07 19:15:58 +02:00
Yves Senn
9f494a9a34 test cleanup, remove ruby_type because it's no longer needed
All tests with a custom inheritance_column use the `Vegtable` model.
The field ruby_type on the Company models is no longer needed
2012-09-03 20:38:14 +02:00
Yves Senn
77ca2815f5 rewrite inheritance tests with a custom inheritance_column
previously the tests with and without a custom `inheritance_column`
used the same models. Since the model then has both fields this can lead
to false positives.
2012-09-03 20:30:43 +02:00
Yves Senn
20574956d1 set the configured #inheritance_column on #become (#7503)
I had to create a new table because I needed an STI table,
which does not have both a "type" and a "custom_type"

the test fails with:
  1) Error:
test_alt_becomes_works_with_sti(InheritanceTest):
NoMethodError: undefined method `type=' for #<Cabbage id: 1, name: "my cucumber", custom_type: "Cucumber">
    /Users/username/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:432:in `method_missing'
    /Users/username/Projects/rails/activerecord/lib/active_record/attribute_methods.rb💯in `method_missing'
    /Users/username/Projects/rails/activerecord/lib/active_record/persistence.rb:165:in `becomes'
    test/cases/inheritance_test.rb:134:in `test_becomes_works_with_sti'
    test/cases/inheritance_test.rb:140:in `test_alt_becomes_works_with_sti'
2012-09-03 16:08:16 +02:00
Dave Desrochers
ff0d9b93b9 reset_counters() was crashing when there were multiple belongs_to associations with the same foreign key.
This closes #5200.
2012-08-21 14:10:11 -03:00
Ari Pollak
53ca22f2e1 Fix occasional microsecond conversion inaccuracy
ActiveRecord::ConnectionAdapters::Column#microseconds did an unnecessary
conversion to from Rational to float when calculating the integer number
of microseconds. Some terminating decimal numbers in base10 are
repeating decimal numbers in base2 (the format of float), and
occasionally this causes a rounding error.
Patch & explanation originally from Logan Bowers.
2012-08-15 13:21:57 -04:00
Andrew White
46492949b8 Improve the derivation of HABTM assocation join table names
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

Also as part of this commit the validity checks for HABTM assocations have
been moved to ActiveRecord::Reflection One side effect of 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.
2012-06-22 06:27:11 +01:00