Commit Graph

4375 Commits

Author SHA1 Message Date
Rafael Mendonça França
fec1028d08 Merge pull request #13201 from marcandre/find_in_batch_enumerator
`find_in_batches` now returns an `Enumerator`

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/lib/active_record/relation/batches.rb
2014-01-29 17:53:10 -02:00
Godfrey Chan
40f0257e05 enum now raises on "dangerous" name conflicts
Dangerous name conflicts includes instance or class method conflicts
with methods defined within `ActiveRecord::Base` but not its ancestors,
as well as conflicts with methods generated by other enums on the same
class.

Fixes #13389.
2014-01-29 10:54:51 -08:00
Godfrey Chan
7e8e91c439 scope now raises on "dangerous" name conflicts
Similar to dangerous attribute methods, a scope name conflict is
dangerous if it conflicts with an existing class method defined within
`ActiveRecord::Base` but not its ancestors.

See also #13389.

*Godfrey Chan*, *Philippe Creux*
2014-01-29 10:54:51 -08:00
Godfrey Chan
9ed66648b5 Fixed a bug in AR::Base#respond_to?
Before:

  >> ActiveRecord::Base.respond_to?(:find_by_something)
  NoMethodError: undefined method `abstract_class?' for Object:Class

After:

  >> ActiveRecord::Base.respond_to?(:find_by_something)
  => false
2014-01-29 10:53:48 -08:00
Mauricio Linhares
66e533f9b1 Correctly send the string given to lock! and reload(:lock) to the lock scope - fixes #13788
As per the documentation at lock!, if the :lock option is a string it should use the given SQL to generate the lock statement.
2014-01-29 12:37:00 -03:00
Tsutomu Kuroda
c1d9934447 Handle aliased attributes in AR::Relation#select, #order, etc.
With this we can write `Model#select(:aliased)`, `Model#order(:aliased)`,
`Model#reoder(aliased: :desc)`, etc.

Supplementary work to 54122067acaad39b277a5363c6d11d6804c7bf6b.
2014-01-29 09:16:46 +09:00
Carlos Antonio da Silva
b9cd5a29dd Fix indent on test case [ci skip] 2014-01-28 08:16:32 -02:00
Kuldeep Aggarwal
20317f3d4d use the new clear_validators! api everywhere to reset validators in tests 2014-01-28 00:13:35 +05:30
Yves Senn
220ee0c74a Merge pull request #13785 from kuldeepaggarwal/fix-find_with_multiple_ids
Fix `ActiveRecord::RecordNotFound` error message with custom primary key
2014-01-24 15:13:16 -08:00
Kuldeep Aggarwal
3a0ddf3394 Fix ActiveRecord::RecordNotFound error message with custom primary key 2014-01-25 02:29:23 +05:30
Vipul A M
9b254df181 Remove unused assignment to fix warnings in enum test. 2014-01-24 12:14:02 +05:30
Kelsey Schlarman
43675f014c Calling reset on a collection association should unload the assocation
Need to define #reset on CollectionProxy.
2014-01-21 18:24:28 -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
Rafael Mendonça França
9383de42a2 Merge pull request #13776 from rails/dirty-enum
Implement the Dirty API with the Enum feature correctly.

Conflicts:
	activerecord/CHANGELOG.md
2014-01-21 20:37:45 -02:00
Rafael Mendonça França
b0a8ef140e has_one and belongs_to accessors don't add ORDER BY to the queries anymore.
Since Rails 4.0, we add an ORDER BY in the `first` method to ensure consistent
results among different database engines. But for singular associations this
behavior is not needed since we will have one record to return. As this
ORDER BY option can lead some performance issues we are removing it for singular
associations accessors.

Fixes #12623.
2014-01-21 14:41:52 -02:00
Yves Senn
e011258c30 prepend table name for Relation#select columns.
This fixes a bug where `select(:id)` combined with `joins()` raised:

```
ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous column name: id:
SELECT  id, authors.author_address_id
FROM "posts"
INNER JOIN "authors"
ON "authors"."id" = "posts"."author_id"
ORDER BY posts.id LIMIT 3
```

The `select_values` are still String and Symbols because other parts (mainly calculations.rb)
rely on that fact.

/cc @tenderlove
2014-01-21 17:21:20 +01:00
Rafael Mendonça França
a0520fceff Add more tests for the dirty feature for enums 2014-01-21 12:45:58 -02:00
Rafael Mendonça França
a57a2bcf4a Make enum feature work with dirty methods
To make this possible we have to override the save_changed_attribute
hook.
2014-01-21 12:45:53 -02:00
Alexander Balashov
691709dd67 Fail early with "Primary key not included in the custom select clause" in find_in_batches
Before this patch find_in_batches raises this error only on second iteration. So you will know about the problem only when you get the batch size threshold.
2014-01-21 17:27:34 +04: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
Rafael Mendonça França
b1b21f9325 Merge pull request #13745 from nextgearcapital/master
set encoding for pipe to binary mode
2014-01-19 10:24:22 -08:00
Godfrey Chan
7386ffc781 Restore ActiveRecord states after a rollback for models w/o callbacks
This fixes a regression (#13744) that was caused by 67d8bb9.

In 67d8bb9, we introduced lazy rollback for records, such that the
record's internal states and attributes are not restored immediately
after a transaction rollback, but deferred until they are first
accessed.

This optimization is only performed when the model does not have any
transactional callbacks (e.g. `after_commit` and `after_create`).

Unfortunately, the models used to test the affected codepaths all
comes with some sort of transactional callbacks. Therefore this
codepath remains largely untested until now and as a result there are
a few issues in the implementation that remains hidden until now.

First, the `sync_with_transaction_state` (or more accurately,
`update_attributes_from_transaction_state`) would perform the
synchronization prematurely before a transaction is finalized (i.e.
comitted or rolled back). As a result, when the actuall rollback
happens, the record will incorrectly assumes that its internal states
match the transaction state, and neglect to perform the restore.

Second, `update_attributes_from_transaction_state` calls `committed!`
in some cases. This in turns checks for the `destroyed?` state which
also requires synchronization with the transaction stae, which causes
an infnite recurrsion.

This fix works by deferring the synchronization until the transaction
has been finalized (addressing the first point), and also unrolled
the `committed!` and `rolledback!` logic in-place (addressing the
second point).

It should be noted that the primary purpose of the `committed!` and
`rolledback!` methods are to trigger the relevant transactional
callbacks. Since this code path is only entered when there are no
transactional callbacks on the model, this shouldn't be necessary. By
unrolling the method calls, the intention here (to restore the states
when necessary) becomes more clear.
2014-01-18 11:16:52 -08:00
Aaron Patterson
c1bbf1b2e4 test to ensure bad prepared statements raise a StatementInvalid exception 2014-01-17 14:08:00 -08:00
Anna Carey
0e9144dcec set encoding to binmode for pipe 2014-01-17 16:49:10 -05:00
Jonathan Baudanza
a099d7d97f psql implementation of #index_name_exists? 2014-01-16 15:00:27 -08:00
Carlos Antonio da Silva
49223c9bc9 Extract a method to simplify setup code 2014-01-16 18:52:43 -02:00
Carlos Antonio da Silva
740cf33b5e Use minitest's skip rather than conditionals + early returns 2014-01-16 18:48:51 -02:00
Carlos Antonio da Silva
44e5551054 Move AR test classes inside the test case 2014-01-16 18:45:03 -02:00
Carlos Antonio da Silva
c9c4a427e1 Do not set up a variable used only in two tests
Just create a local variable whenever we need the record, rather than
doing an extra find for every test on the setup method.
2014-01-16 18:40:18 -02:00
Carlos Antonio da Silva
07ff3525d5 No need for instance vars on single tests 2014-01-16 18:40:18 -02:00
Carlos Antonio da Silva
da4b5e8ecb Cleanup duplicated setup of callbacks in transactions tests 2014-01-16 18:40:18 -02:00
Carlos Antonio da Silva
7b11b06e6d No need to use #send with public methods 2014-01-16 18:40:17 -02:00
Harry Brundage
177989c6c0 Make AR::Base#touch fire the after_commit and after_rollback callbacks 2014-01-16 09:05:59 -02:00
Carlos Antonio da Silva
38fcee3871 Fix test for cache_key + touched
Ensure the child can actually be touched. The `Bulb` model has no
timestamp column, thus trying to touch it would return `nil`.
2014-01-16 09:05:55 -02:00
Yves Senn
6eab530429 reset column information after fiddling with Encoding.default_internal
This solves order depndent problems in `base_test.rb`. The leaked column
information crashed test cases using the `Weird` class later on:

```
  2) Error:
BasicsTest#test_group_weirds_by_from:
SyntaxError: /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:387: invalid hex escape
... attribute_before_type_cast("\x{A4CA}\x{A4DE}\x{A4A8}", *arg...
...                               ^
/Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:387: invalid hex escape
...te_before_type_cast("\x{A4CA}\x{A4DE}\x{A4A8}", *args)
...                               ^
/Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:387: invalid hex escape
...e_type_cast("\x{A4CA}\x{A4DE}\x{A4A8}", *args)
...                               ^
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:385:in `module_eval'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:385:in `define_proxy_call'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:294:in `block in define_attribute_method'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:285:in `each'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:285:in `define_attribute_method'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:252:in `block in define_attribute_methods'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:252:in `each'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:252:in `define_attribute_methods'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_methods.rb:72:in `block in define_attribute_methods'
    /Users/senny/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/mutex_m.rb:73:in `synchronize'
    /Users/senny/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/mutex_m.rb:73:in `mu_synchronize'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_methods.rb:69:in `define_attribute_methods'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_methods.rb:174:in `method_missing'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:45:in `public_send'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:45:in `_assign_attribute'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:32:in `block in assign_attributes'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:26:in `each'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:26:in `assign_attributes'
    /Users/senny/Projects/rails/activerecord/lib/active_record/core.rb:458:in `init_attributes'
    /Users/senny/Projects/rails/activerecord/lib/active_record/core.rb:191:in `initialize'
    /Users/senny/Projects/rails/activerecord/lib/active_record/inheritance.rb:30:in `new'
    /Users/senny/Projects/rails/activerecord/lib/active_record/inheritance.rb:30:in `new'
    /Users/senny/Projects/rails/activerecord/lib/active_record/persistence.rb:33:in `create'
    test/cases/base_test.rb:646:in `test_group_weirds_by_from'
```
2014-01-16 09:34:49 +01:00
Yves Senn
fca8b0318e we have with_env_tz as global test helper. Remove duplicate. 2014-01-16 09:34:49 +01:00
Yves Senn
a713900839 isolate class attribute assignment in migration_test.rb
This makes the tests inside `migration_test.rb` order independent.
The assignments to `Reminder.table_name_prefix` and `Reminder.table_name_suffix`
previously leaked and had impact on following test cases.

This patch isolates the assignments on a throw-away subclass.
2014-01-16 09:33:45 +01:00
Yves Senn
f00524375d use teardown for cleanup, not setup.
This solves order dependent issues where the last test
leaked the query cache state. This resulted in the following error:

```
QueryCacheExpiryTest#test_cache_is_expired_by_habtm_delete [test/cases/query_cache_test.rb:275]:
not all expectations were satisfied
unsatisfied expectations:
- expected exactly twice, invoked once: #<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x7f93e0c65838>.clear_query_cache(any_parameters)
```
2014-01-16 09:33:45 +01:00
Yves Senn
8e1735e26c tests without transactional fixtures need to cleanup afterwards.
This fixes test order issues.
2014-01-16 09:33:45 +01:00
Yves Senn
a6512cbd6c no need to return skip in tests. skip is enough. 2014-01-16 09:33:45 +01:00
Aaron Patterson
8d146c8bec rm dup code
e64a83cdbd/activerecord/test/cases/relation/merging_test.rb (L80-91)
2014-01-14 17:47:10 -08:00
Aaron Patterson
ce95fb2991 "string" isn't a valid column type for ActiveRecord
Conflicts:
	activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
2014-01-14 14:01:10 -08:00
Yves Senn
b23330745b don't establish a new connection when testing with sqlite3_mem.
This fixes broken `rake test_sqlite3_mem` suite for Active Record.
The problem is that that the old database with the schema is lost
when establishing a new connection. Upon reconnting we are left
with a blank database and tests down the line start failing.
2014-01-14 18:03:31 +01:00
Cody Cutrer
547ed45633 sqlite >= 3.8.0 supports partial indexes 2014-01-14 08:53:32 -07:00
Ujjwal Thaakar
e8d1d84837
Don't try to get the subclass if the inheritance column doesn't exist
The `subclass_from_attrs` method is called even if the column specified by
the `inheritance_column` setting doesn't exist. This prevents setting associations
via the attributes hash if the association name clashes with the value of the setting,
typically `:type`. This worked previously in Rails 3.2.
2014-01-14 18:53:45 +05:30
Godfrey Chan
b242b2dbe7 Enum mappings are now exposed via class methods instead of constants.
Example:

    class Conversation < ActiveRecord::Base
      enum status: [ :active, :archived ]
    end

Before:

    Conversation::STATUS # => { "active" => 0, "archived" => 1 }

After:

    Conversation.statuses # => { "active" => 0, "archived" => 1 }
2014-01-14 04:00:34 -08:00
Yves Senn
f6ca00bd43 Merge pull request #13669 from chulkilee/name-error-name
Set NameError#name
2014-01-14 00:12:54 -08:00
Aaron Patterson
f1764a2de1 unscope should remove bind values associated with the where 2014-01-13 16:15:20 -08:00
Aaron Patterson
d220e8add9 recover from test runs that leave the database in a bad state 2014-01-13 15:02:28 -08:00
Chulki Lee
bea44cbaa4 Set NameError#name 2014-01-13 12:47:14 -08:00
Yves Senn
e95031f55d fix bug in becomes! when changing from base to subclass. Closes #13272. 2014-01-13 15:07:14 +01:00
Yves Senn
792c66f868 use enum labels as form values. Achieved by _before_type_cast.
Closes #13650, #13672

This is an alternate implementation to solve #13650. Currently form fields
contain the enum value (eg. "1"). This breaks because the setter `enum=`
expects the label (eg. "active").

ActiveRecord::Enum allows you to use labels in your application but store numbers.
We should make sure that all parts after AR are dealing with labels and not the
underlying mapping to a number.

This patch defines `_before_type_cast` on every enum column to return the label.
This method is later used to fetch the value to display in form fields.

I deliberately copied the implementation of the enum getter instead of delegating to it.
This allows you to overwrite the getter and for example return a `Value Object` but have it
still work for form fields.
2014-01-11 12:57:09 +01:00
Prathamesh Sonpatki
e633cdb34a Restore DATABASE_URL even if it's nil in connection_handler test
- We have to restore DATABASE_URL to its previous state irrespective of
  previous value is nil or not
2014-01-10 10:06:19 +05:30
schneems
6cc03675d3 Ensure Active Record connection consistency
Currently Active Record can be configured via the environment variable `DATABASE_URL` or by manually injecting a hash of values which is what Rails does, reading in `database.yml` and setting Active Record appropriately. Active Record expects to be able to use `DATABASE_URL` without the use of Rails, and we cannot rip out this functionality without deprecating. This presents a problem though when both config is set, and a `DATABASE_URL` is present. Currently the `DATABASE_URL` should "win" and none of the values in `database.yml` are used. This is somewhat unexpected to me if I were to set values such as `pool` in the `production:` group of `database.yml` they are ignored.

There are many ways that active record initiates a connection today:

- Stand Alone (without rails)
  - `rake db:<tasks>`
  - ActiveRecord.establish_connection
 
- With Rails
  - `rake db:<tasks>`
  - `rails <server> | <console>`
  - `rails dbconsole`


We should make all of these behave exactly the same way. The best way to do this is to put all of this logic in one place so it is guaranteed to be used.

Here is my prosed matrix of how this behavior should work:

```
No database.yml
No DATABASE_URL
=> Error
```

```
database.yml present
No DATABASE_URL
=> Use database.yml configuration
```

```
No database.yml
DATABASE_URL present
=> use DATABASE_URL configuration
```

```
database.yml present
DATABASE_URL present
=> Merged into `url` sub key. If both specify `url` sub key, the `database.yml` `url`
   sub key "wins". If other paramaters `adapter` or `database` are specified in YAML,
   they are discarded as the `url` sub key "wins".
```

### Implementation

Current implementation uses `ActiveRecord::Base.configurations` to resolve and merge all connection information before returning. This is achieved through a utility class: `ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig`.

To understand the exact behavior of this class, it is best to review the behavior in activerecord/test/cases/connection_adapters/connection_handler_test.rb though it should match the above proposal.
2014-01-09 16:35:37 -06:00
Yves Senn
724509a9d5 make change_column_null reversible. Closes #13576.
Closes #13623.
2014-01-08 15:51:06 +01:00
Damien Mathieu
a334425caf create/drop test and development databases only if RAILS_ENV is nil
Closes #13625
2014-01-08 14:37:07 +01:00
Rafael Mendonça França
f12413295b Merge pull request #13355 from dylanahsmith/migration-version
activerecord: Initialize Migration with version from MigrationProxy.

Conflicts:
	activerecord/CHANGELOG.md
2014-01-07 18:44:51 -02:00
Roderick van Domburg
9330631888 Auto-generate stable fixture UUIDs on PostgreSQL.
Fixes: #11524
2014-01-07 19:05:50 +01:00
Nishant Modak
eb589fed6f Make change_table use object of current database adapter
- Earlier, change_table was creating database-agnostic object.
  - After this change, it will create correct object based on current
    database adapter.
  - This will ensure that create_table and change_table will get same objects.
  - This makes update_table_definition method public and nodoc.
  - Fixes #13577 and #13503
2014-01-07 15:57:21 +05:30
Dylan Thacker-Smith
06ace1e2b5 activerecord: Initialize Migration with version from MigrationProxy. 2014-01-06 10:46:35 -05:00
Thales Oliveira
901a0c8b4a Fix: ActiveRecord::Store TypeError conversion when using YAML coder
Renaming the test accordingly to its behaviour

Adding 'Fixes' statement to changelog

Improving tests legibility & changelog

Undoing mistakenly removed empty line & further improving changelog
2014-01-06 11:36:19 -02:00
Matthias Zirnstein
bf556880f2 Remove method redefined warnings for test suite
has_many definitions with "name" as singular and as plural e.g.
  has_many :welcome_posts_with_comment
  has_many :welcome_posts_with_comments

Ruby mentions it with:

lib/active_record/associations/builder/collection_association.rb:65:
  warning: method redefined; discarding old welcome_posts_with_comment_ids
lib/active_record/associations/builder/collection_association.rb:65:
  warning: previous definition of welcome_posts_with_comment_ids was here
lib/active_record/associations/builder/collection_association.rb:75:
  warning: method redefined; discarding old welcome_posts_with_comment_ids=
lib/active_record/associations/builder/collection_association.rb:75:
  warning: previous definition of welcome_posts_with_comment_ids= was here
2014-01-05 18:18:07 +01:00
T.J. Schuck
72bb3fc297 Change all "can not"s to the correct "cannot". 2014-01-03 17:02:31 -05:00
Rafael Mendonça França
19b2188e6c Merge pull request #10134 from derikson/collection_proxy_select_with_multiple_args
Change CollectionProxy#select to take the same arguments as ActiveRecord::select
2014-01-03 13:03:19 -08:00
Godfrey Chan
788bb40e38 Building new records with enum scopes now works as expected
Previously, this would give an `ArgumentError`:

   class Issue < ActiveRecord::Base
     enum :status, [:open, :finished]
   end

   Issue.open.build # => ArgumentError: '0' is not a valid status
   Issue.open.create # => ArgumentError: '0' is not a valid status

PR #13542 muted the error, but the issue remains. This commit fixes
the issue by allowing the enum value to be written directly via the
setter:

   Issue.new.status = 0 # This now sets status to :open

Assigning a value directly via the setter like this is not part of the
documented public API, so users should not rely on this behavior.

Closes #13530.
2014-01-03 09:31:01 -08:00
Rafael Mendonça França
358abe4524 Merge pull request #13542 from robin850/issue-13530
Fix enum writers when using integers
2014-01-01 19:17:59 -02:00
Rafael Mendonça França
f141919974 Add CHANGELOG entry for #13557 [ci skip] 2014-01-01 19:08:28 -02:00
Rafael Mendonça França
a28f1c2793 Merge pull request #13557 from gmarik/patch-1
Use `Array#wrap` instead `Array()`
2014-01-01 19:04:29 -02:00
Robin Dupret
7aebcb67b0 Fix the enums writer methods
Previously, the writer methods would simply check whether the passed
argument was the symbol representing the integer value of an enum field.
Therefore, it was not possible to specify the numeric value itself but
the dynamically defined scopes generate where clauses relying on this
kind of values so a chained call to a method like `find_or_initialize_by`
would trigger an `ArgumentError`.

Reference #13530
2014-01-01 17:57:34 +01:00
Rafael Mendonça França
da0463cf5e Improve the tests to not call assert_nothing_raised 2014-01-01 14:15:01 -02:00
Rafael Mendonça França
b94e2dd82c Merge pull request #13550 from vipulnsward/13437-fix
Fix for #13437

Conflicts:
	activerecord/CHANGELOG.md
2014-01-01 14:14:45 -02:00
Rafael Mendonça França
e015f4e2e3 Merge pull request #13556 from yahonda/update_mysql_grant
Update grant statement to address #13549
2014-01-01 07:38:15 -08:00
Yasuo Honda
85a1f7ae1e Change the inexistent database name to inexistent_activerecord_unittest
to make this grant statement described in the document works

GRANT ALL PRIVILEGES ON inexistent_activerecord_unittest.* to 'rails'@'localhost';
2014-01-01 09:38:37 +09:00
Amr Tamimi
e0ad9ae27e Add the ability to nullify the enum column 2014-01-01 01:48:15 +02:00
Rafael Mendonça França
13c18fe2ca Improve tests to use only public API 2013-12-31 21:04:11 -02:00
gmarik
aaf1af3cb8 add test case 2013-12-31 13:46:33 -06:00
Washington Luiz
8e1f26c66c Make outer joins on proper parent
Outer joins were being built on the root relation klass rather than the
one specified in the join dependency root
2013-12-31 01:10:38 -03:00
Vipul A M
bb17c3b210 2075f39d72 introduced a regression in includes/preloades
by calling `read_attribute` on an association when preloading takes places, instead of using loaded records in `association.target`.

tl;dr

Records are not made properly available via `read_attribute` when preloding in simultaneous,
but value of `@loaded` is already set true, and records concatenated in `association.target` on an association object.
When `@loaded` is true we return an object of `AlreadyLoaded` in preload_for. In `AlreadyLoaded` to return preloaded
records we make wrong use of `read_attribute`, instead of `target` records.

The regression is fixed by making use of the loaded records in `association.target` when the preloading takes place.

Fixes #13437
2013-12-31 02:47:37 +05:30
schneems
5b96027ef6 Allow "url" sub key in database.yml configuration
Currently a developer can pass in a YAML configuration that fully specifies connection information:

```
production:
  database: triage_production
  adapter: password
  pool: 5
```

They can also pass in a string that specifies a connection URL directly to an environment key:

```
production: postgresql://localhost/foo
```

This PR allows the use of both a connection url and specifying connection attributes via YAML through the use of the "url" sub key:

```
production:
  url: postgresql://localhost/foo
  pool: 3
```

This will allow developers to inherit Active Record options such as `pool` from `&defaults` and still use a secure connection url such as `<%= ENV['DATABASE_URL'] %>`. The URL is expanded into a hash and then merged back into the YAML hash. If there are any conflicts, the values from the connection URL are preferred. 

Talked this over with @josevalim
2013-12-30 12:21:14 -05:00
José Valim
10721450de Merge pull request #13527 from kuldeepaggarwal/f-independent-specs
Use user-defined configurations in mysql tests
2013-12-29 12:32:06 -08:00
Kuldeep Aggarwal
a2985e2067 raise ArgumentError exception if Model.where.not is called with nil argument 2013-12-30 01:53:02 +05:30
Kuldeep Aggarwal
143da09f51 used user-defined configurations for running tests that might depend on user's system configuration 2013-12-29 13:57:52 +05:30
Yves Senn
4fd3204a04 Merge pull request #13474 from jdelStrother/becomes
Copy changed_attributes across to newly become'd records
2013-12-27 11:15:19 -08:00
Jonathan del Strother
b7bf025374 Copy changed_attributes across to newly become'd records
Without this, the original record's values won't get saved, since the partial insertions support (144e8691cb) checks for changed values and thinks there are none.
2013-12-27 15:54:06 +00:00
schneems
2409c61661 Fix failure introduced from #13488 2013-12-25 18:45:26 -05:00
Guillermo Iguaran
278bbfd7df Merge pull request #13478 from schneems/schneems/fix-mysql
Move mysql2 test for when adapter will be loaded
2013-12-25 12:21:38 -08:00
Kuldeep Aggarwal
b9d79b1f5f using symbol instead of string in establish_connection 2013-12-25 15:24:25 +05:30
schneems
8e2c0803f5 Move mysql2 test for when adapter will be loaded
When run with only the Mysql adapter, we get this failure: https://travis-ci.org/rails/rails/jobs/15937907#L2416

Porting the test over to only run when mysql2 is loaded
2013-12-24 17:28:40 -05:00
schneems
f0311c2487 Raise NoDatabaseError when db does not exist
Building on the work of #13427 this PR adds a helpful error message to the adapters: mysql, mysql2, and sqlite3
2013-12-24 10:13:12 -05:00
José Valim
ec11807368 Deprecate use of string in establish_connection as connection lookup 2013-12-24 10:18:54 +01:00
José Valim
d2ed433b0a Only build a ConnectionSpecification if required 2013-12-24 10:02:07 +01:00
José Valim
33cb2f334d Merge pull request #13463 from josevalim/jv-env
Do not store production information in .yml files
2013-12-23 12:28:04 -08:00
José Valim
c390e60811 Guarantee the connection resolver handles string values
This commit also cleans up the rake tasks that were checking
for DATABASE_URL in different places.

In fact, it would be nice to deprecate DATABASE_URL usage in the long
term, considering the direction we are moving of allowing those in .yml
files.
2013-12-23 20:15:52 +01:00
Carlos Antonio da Silva
9e1740af9c Tidy up fix for PG extensions quoting
Always pass in the column for quote_bound_value and quote using it in
case it exists there.
2013-12-23 16:28:35 -02:00
Tadas Tamosauskas
73bba4c1e1 Serialize postgres' hstore, json and array types correctly in AR update methods.
Fixes #12261. Closes #12395.

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/test/cases/adapters/postgresql/array_test.rb
	activerecord/test/cases/adapters/postgresql/json_test.rb
2013-12-23 16:27:54 -02:00
Carlos Antonio da Silva
56510091fb Do not consider PG array columns as number or text columns
The code uses these checks in several places to know what to do with a
particular column, for instance AR attribute query methods has a branch
like this:

    if column.number?
      !value.zero?
    end

This should never be true for array columns, since it would be the same
as running [].zero?, which results in a NoMethodError exception.

Fixing this by ensuring that array columns in PostgreSQL never return
true for number?/text? checks.

Since most of the array support was based on the postgres_ext lib, it's
worth noting it does the same thing for numeric array columns too:

https://github.com/dockyard/postgres_ext/blob/v1.0.0/lib/postgres_ext/active_record/connection_adapters/postgres_adapter.rb#L72

This extended the same logic for text columns to ensure consistency.
2013-12-23 16:26:15 -02:00
schneems
0ec45cd15d Tell how to Create a Database in Error Message
Currently if you attempt to use a database that does not exist  you get an error:

```
PG::ConnectionBad FATAL:  database "db_error" does not exist
```

The solution is easy, create and migrate your database however new developers may not know these commands by memory. Instead of requiring the developer to search for a solution, tell them how to fix the problem in the error message:

```
ActiveRecord::NoDatabase: FATAL:  database "db_error" does not exist
Run `$ bin/rake db:create db:migrate` to create your database
```

Active Record should not know about `rake db:migrate` so this additional information needs to come from the railtie. Potential alternative implementation suggestions are welcome.
2013-12-23 10:23:48 -05:00
Paul Nikitochkin
2bcf7158d3 On destroying do not touch destroyed belongs to association.
Fixes: #13445
2013-12-23 15:44:48 +02:00
Yves Senn
00fc64a6dc Merge pull request #13446 from kuldeepaggarwal/resolver-test-cases
Resolver test cases
2013-12-23 05:14:14 -08:00
Kuldeep Aggarwal
34f17b871e added test cases for Resolver#connection_url_to_hash 2013-12-23 16:45:00 +05:30
Damien Mathieu
1f6a9b50ee fix quoting non-strings
Closes #13444
2013-12-22 17:00:50 +01:00
Aaron Patterson
fbb79b517f fix url connections for sqlite3 2013-12-20 16:13:34 -08:00
Rafael Mendonça França
ccaa3e47c4 Merge pull request #13412 from arthurnn/quote_id_not_id
quoting: Check if id is a valid method before using it
2013-12-19 13:57:14 -08:00
Arthur Neves
4a720a2cde quoting: Check if id is a valid method before using it
Need to check if valud also respond_to :id before calling it, otherwise
things could explode.
2013-12-19 16:51:28 -05:00
Cody Cutrer
847e9a95da fix default select when from is used 2013-12-19 14:40:13 -07:00
Carlos Antonio da Silva
e4cde5d58c Fix indent in PG array tests
[ci skip]
2013-12-19 19:14:23 -02:00
Carlos Antonio da Silva
cc1f0b4c2d Merge pull request #13395 from kuldeepaggarwal/postgres-table-ref-regex
modified regex for finding table_name from a multiline sql query in postgresql
2013-12-19 05:22:28 -08:00
Kuldeep Aggarwal
b082bece5e Fix PostgreSQL insert to properly extract table name from multiline string SQL.
Previously, executing an insert SQL in PostgreSQL with a command like this:

    insert into articles(
      number)
    values(
      5152
    )

would not work because the adapter was unable to extract the correct articles table name.
2013-12-19 18:46:17 +05:30
Carlos Antonio da Silva
c5b76b5362 Prefer assert_raise instead of flunk + rescue to test for exceptions
Change most tests to make use of assert_raise returning the raised
exception rather than relying on a combination of flunk + rescue to
check for exception types/messages.
2013-12-19 09:20:51 -02:00
Carlos Antonio da Silva
5b0fc1a007 Merge pull request #13393 from matthewd/fix_pg_range_tests
Fix PostgreSQL range tests on fresh DB

Correcting the name of the table we're creating is self-explanatory.

But we must also move away from the low IDs, because we're not touching the freshly-created primary key sequence; when the time comes, @new_range will be assigned an ID of 1.
2013-12-19 01:44:01 -08:00
Kuldeep Aggarwal
ff4673be52 set encoding UTF-8 for accepting multibyte character 2013-12-19 11:00:38 +05:30
Godfrey Chan
e63748cd37 Merge pull request #13366 from vipulnsward/minitest-namespace-change
Change all `MiniTest` to `Minitest`
2013-12-18 19:22:30 -08:00
Matthew Draper
f8b4110f00 Fix PostgreSQL range tests
The changes in c4044b2 meant the tests would error on a fresh DB.
2013-12-19 13:34:46 +10:30
rono23
ee738f9604 Fix to_param when attribute has multibyte character 2013-12-19 05:29:16 +09:00
Vipul A M
7bae2921ec Change all MiniTest to Minitest since, MiniTest namespace has been renamed to Minitest
Ref: https://github.com/seattlerb/minitest/blob/master/History.txt
2013-12-18 14:39:50 +05:30
Jeremy Kemper
c141dfc838 Add a failing test for assigning nil to a polymorphic belongs_to not nullifying its _type column 2013-12-17 21:45:55 -07:00
Jeremy Kemper
2b096c7170 Merge pull request #13314 from laurocaetano/blacklist_array_methods
Create a blacklist to disallow mutator methods to be delegated to Array

Conflicts:
	guides/source/upgrading_ruby_on_rails.md
2013-12-17 11:29:23 -07:00
Carlos Antonio da Silva
ae196e85ee Merge pull request #13341 from carlosantoniodasilva/ca-i18n
Default I18n.enforce_available_locales to true

We will default this option to true from now on to ensure users properly handle their list of available locales whenever necessary. This option was added as a security measure and thus Rails will follow it defaulting to secure option.

Also improve the handling of I18n config options in its railtie, taking the new enforce_available_locales option into account, by setting it as the last one in the process. This ensures no other configuration will trigger a deprecation warning due to that setting.
2013-12-17 08:22:26 -08:00
Lauro Caetano
d4ee09cda1 Create a blacklist to disallow mutator methods to be delegated to Array.
This change was necessary because the whitelist wouldn't work.
It would be painful for users trying to update their applications.

This blacklist intent to prevent odd bugs and confusion in code that call mutator
methods directely on the `Relation`.
2013-12-17 13:43:10 -02:00
Rafael Mendonça França
c56bbaaf6f Merge pull request #13343 from akshay-vishnoi/test-cases
test case for #limit added - picking latest value from limit
2013-12-17 06:23:05 -08:00
Carlos Antonio da Silva
6802196a6b Disable available locales checks to avoid warnings running the tests 2013-12-17 09:05:41 -02:00
Akshay Vishnoi
687cd75fb5 test case for #limit added - picking latest value from limit 2013-12-17 03:50:34 +05:30
Martin Emde
8062a30794 Better support for where() conditions that use an association name.
Using the name of an association in `where` previously worked only
if the value was a single `ActiveRecrd::Base` object. e.g.

    Post.where(author: Author.first)

Any other values, including `nil`, would cause invalid SQL to be
generated. This change supports arguments in the `where` query
conditions where the key is a `belongs_to` association name and the
value is `nil`, an `Array` of `ActiveRecord::Base` objects, or an
`ActiveRecord::Relation` object.

    # Given the Post model
    class Post < ActiveRecord::Base
      belongs_to :author
    end

    # nil value finds records where the association is not set
    Post.where(author: nil)
    # SELECT "posts".* FROM "posts" WHERE "posts"."author_id" IS NULL

    # Array values find records where the association foreign key
    # matches the ids of the passed ActiveRecord models, resulting
    # in the same query as Post.where(author_id: [1,2])
    authors_array = [Author.find(1), Author.find(2)]
    Post.where(author: authors_array)

    # ActiveRecord::Relation values find records using the same
    # query as Post.where(author_id: Author.where(last_name: "Emde"))
    Post.where(author: Author.where(last_name: "Emde"))

Polymorphic `belongs_to` associations will continue to be handled
appropriately, with the polymorphic `association_type` field added
to the query to match the base class of the value. This feature
previously only worked when the value was a single `ActveRecord::Base`.

    class Post < ActiveRecord::Base
      belongs_to :author, polymorphic: true
    end

    Post.where(author: Author.where(last_name: "Emde"))
    # Generates a query similar to:
    Post.where(author_id: Author.where(last_name: "Emde"), author_type: "Author")
2013-12-16 14:16:15 -08:00
Cody Cutrer
75a2e4a8df support creating temporary tables from queries
also override drop_table in AbstractMySQLAdapter to properly drop
temporary tables without committing the transaction
2013-12-14 07:07:10 -07:00
Rafael Mendonça França
1713e8fe16 Merge pull request #13306 from kassio/master
Fix mysql to support duplicated column names
2013-12-13 05:55:54 -08:00
Kassio Borges
b8569b9337 Fix mysql to support duplicated column names
This will fix the [broken
test](4a26508366)
 `test_with_limiting_with_custom_select`.

The query's result was built in a hash with column name as key, if the
result have a duplicated column name the last value was
overriding the first one.
2013-12-13 11:55:13 -02:00
Yves Senn
63f9a7507b refactor, reuse assertions in range_test.rb. 2013-12-13 14:28:13 +01:00
Yves Senn
c4044b2f8a extract PG range tests from datatype_test.rb into range_test.rb 2013-12-13 14:17:21 +01:00
Jeremy Kemper
0b142a6f84 Add a bunch of Relation -> Array delegate methods to the whitelist. This won't last - aim to switch back to a blacklist for mutator methods. 2013-12-12 21:10:03 -07:00
Lauro Caetano
1244aa7c5f Use public_send instead of just use send. 2013-12-12 20:19:04 -02:00
Lauro Caetano
aa85bdba68 Use a whitelist to delegate methods to array 2013-12-12 19:34:47 -02:00
laurocaetano
d1987846b3 Remove delegation test.
This test was removed, since Relation will not delegate class
methods to Array.
2013-12-12 19:31:48 -02:00
Aaron Patterson
da3891c898 make sure cached table name is a string. fixes #12582 2013-12-12 10:47:07 -08:00
Carlos Antonio da Silva
5ef040d0c6 Get rid of hack for freezing time on AR tests
We can now make use of the existent #travel/#travel_to helper methods
added to AS test case and available in all tests.
2013-12-12 08:57:07 -02:00
Rafael Mendonça França
c9b8ca9748 Merge pull request #13264 from laurocaetano/fix_dynamic_finder_with_reserved_words
Prevent invalid code when using dynamic finders with reserved ruby word.
2013-12-11 14:38:27 -08:00
Rafael Mendonça França
7a036ebd30 Revert the whole refactoring in the association builder classes.
This is to get activerecord-deprecated_finders work again
2013-12-11 19:28:32 -02:00
Rafael Mendonça França
e1ce005942 Revert "Merge pull request #12518 from vipulnsward/remove_count_options"
It is needed for activerecord-depecated_finders

This reverts commit dcff027a5242b20c0c90eb062dddb22ccf51aed9, reversing
changes made to 3a2093984ff49d86db1efeff0c7581e788ecfb9f.
2013-12-11 13:29:21 -02:00
Lauro Caetano
23ce3e5fde Prevent invalid code when using dynamic finders with Ruby's reserved words.
The dynamic finder was creating the method signature with the parameters name,
which may have reserved words and this way creating invalid Ruby code.

Closes: #13261

    Example:

        # Before
        Dog.find_by_alias('dog name')

        # Was creating this method
        def self.find_by_alias(alias, options = {})

        # After
        Dog.find_by_alias('dog name')

        # Will create this method
        def self.find_by_alias(_alias, options = {})
2013-12-11 01:00:32 -02:00
Yves Senn
821153525c Merge pull request #13236 from jetthoughts/13230_type_cast_bug_in_agr_functions
Fix type cast on group sum with custom expression
2013-12-10 05:29:25 -08:00
Paul Nikitochkin
2a7fe7ae9b Fix type cast on group sum with custom expression
For PG adapters with custom expression and grouped result
of aggregate functions have not found correct column type
for it. Extract column type from query result.

Closes: #13230
2013-12-10 14:30:12 +02:00
Carlos Antonio da Silva
7cf9a43268 Fix warnings on mysql2 explain test 2013-12-10 08:06:48 -02:00
Jeremy Kemper
2fd067c33b Merge pull request #13248 from yahonda/support_mysql573_explain
Support MySQL 5.7 explain
2013-12-09 23:22:32 -08:00
Yasuo Honda
b6655885ef Remove DEFAULT NULL for primary key column to support MySQL 5.7.3
Since MySQL 5.7.3 m13 does now allow primary key column is null.
2013-12-10 11:12:33 +09:00
Yasuo Honda
75f453ff4c Support MySQL 5.7 explain 2013-12-10 11:04:09 +09:00
Marc-Andre Lafortune
0aad463cfb find_in_batches now returns an Enumerator when called without a block, so that it
can be chained with other `Enumerable` methods.
2013-12-06 08:53:14 -05:00
George Guimarães
ea75eb6499 Add integration test for #12459 2013-12-05 21:32:51 -02:00
Carlos Antonio da Silva
871914c239 Remove deprecated call to Relation#all 2013-12-05 16:32:00 -02:00
Severin Schoepke
f1a646fa74 polymorphic belongs_to association with touch: true updates old record correctly
Example: Given you have a comments model with a polymorphic commentable
association (e.g. books and songs) with the touch option set.
Every time you update a comment its commentable should be touched.
This was working when you changed attributes on the comment or when you
moved the comment from one book to another. However, it was not working
when moving a comment from a book to a song. This is now fixed.
2013-12-05 16:03:07 +01:00
Rafael Mendonça França
c294055a58 Merge pull request #12403 from thedarkone/attr-method-missing-fix
Fix AR#method_missing re-dispatching into overwritten attribute methods

Conflicts:
	activerecord/lib/active_record/attribute_methods.rb
2013-12-04 11:10:47 -02:00
Lauro Caetano
2a517e7291 Fix offset with last.
Closes #7441
2013-12-03 17:09:58 -02:00
Yves Senn
be5527b8e8 connection.type_to_sql returns a String for unmapped types.
Closes #13146.

This fixes an error when using:

```
change_colum :table, :column, :bigint, array: true
```
2013-12-03 17:54:25 +01:00
Carlos Antonio da Silva
5f1e394165 Fix bad usage of #select with hash 2013-12-03 10:45:40 -02:00
Vipul A M
1ed81e85ca Currently, we clear query_cache in cache block finish, even if we may already have cache true.
This commit takes into account the last cache_enabled value, before clearing query_cache.
2013-12-03 17:48:14 +05:30
Victor Costan
ddf27acbc2 Introduce a context for rendering fixtures ERB.
Fixture files are passed through an ERB renderer before being read as
YAML. The rendering is currently done in the context of the main object,
so method definitons leak into other fixtures, and there is no clean
place to define fixture helpers.

After this commit, the ERB renderer will use a new subclass of
ActiveRecord::FixtureSet.context_class each time a fixture is rendered.
2013-12-03 02:52:26 -05:00
Rafael Mendonça França
4a26508366 Make the tests break again
We need to fix this test
2013-12-02 19:45:58 -02:00
Carlos Antonio da Silva
3bc9c35707 Merge pull request #13111 from akshay-vishnoi/typo
Typo fixes [ci skip]
2013-11-30 07:25:00 -08:00
Akshay Vishnoi
e0326f56b4 Typo fixes [ci skip] 2013-11-30 20:27:01 +05:30
Godfrey Chan
35fd2d4019 Raise ArgumentError when has_one is used with counter_cache
Previously, the `has_one` macro incorrectly accepts the `counter_cache` option
due to a bug, although that options was never supported nor functional on
`has_one` and `has_one ... through` relationships. It now correctly raises an
`ArgumentError` when passed that option.

For reference, this bug was introduced in 52f8e4b9.
2013-11-29 19:21:49 -08:00
Kuldeep Aggarwal
647cff3a13 updating options documentation for associations
removed unnecessary test case and improved test case for belongs_to having invalid  options
2013-11-29 18:49:56 +05:30
Yves Senn
83d643407e Merge pull request #13054 from senny/remove_oracle_tests
Remove leftover Oracle tests.
2013-11-27 14:41:44 -08:00
Rafael Mendonça França
5fdbec7dd1 Merge pull request #13061 from laurocaetano/fix-uniqueness-validation-for-aliased-attribute
Fix bug when validating the uniqueness of an aliased attribute.
Conflicts:
	activerecord/CHANGELOG.md
2013-11-26 20:54:19 -02:00
heruku
45d4d141f9 changed update counter to act on unscoped model 2013-11-26 09:04:03 -06:00
Yves Senn
951c9ed31d the oracle adapter lives in a gem. Tests should live there as well. 2013-11-26 15:57:33 +01:00
Yves Senn
e161aeab17 remove leftover firebird adapter tests. 2013-11-26 11:05:37 +01:00
Yves Senn
6eba8d27e6 rename_index: add the new index before removing the old one.
This prevents the following error when a MySQL index on a foreign key
column is renamed:

```
ActiveRecord::StatementInvalid: Mysql2::Error: Cannot drop index 'index_engines_on_car_id': needed in a foreign key constraint: DROP INDEX `index_engines_on_car_id` ON `engines`
```

refs: #13038.
2013-11-26 10:03:55 +01:00
Brian Thomas Storti
5aab0c0538 Raise RecordNotDestroyed when children can't be replaced
Fixes #12812
Raise `ActiveRecord::RecordNotDestroyed` when a child marked with
`dependent: destroy` can't be destroyed.

The following code:
```ruby
class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy
end

class Comment < ActiveRecord::Base
  before_destroy do
    return false
  end
end

post = Post.create!(comments: [Comment.create!])
post.comments = [Comment.create!]
````

would result in a `post` with two `comments`.
With this commit, the same code would raise a `RecordNotDestroyed`
exception, keeping the `post` with the same `comment`.
2013-11-25 19:30:07 -02:00
Ryuta Kamizono
501ae92a32 Only use BINARY for mysql case sensitive uniqueness check when column has a case insensitive collation. 2013-11-26 04:59:18 +09:00
Aaron Patterson
19dd216610 require the files we test 2013-11-25 11:33:31 -08:00
Rafael Mendonça França
a6900a2073 Merge pull request #13034 from vipulnsward/some_typos
Fix some minor typos
2013-11-25 10:49:35 -08:00
Vipul A M
82de1eda7c Fix some minor typos [ci skip] 2013-11-26 00:13:35 +05:30
Yves Senn
7ccb482181 Merge pull request #13029 from akshay-vishnoi/documentation
`delgated` => `delegated`
2013-11-25 00:47:59 -08:00
Akshay Vishnoi
5a406ff42e delgated => delegated 2013-11-25 14:09:44 +05:30
Evgeny Li
c449a74e89 Fix validation on uniqueness of empty association 2013-11-22 22:22:34 +04:00
Yves Senn
e2fbec96d4 replace custom Time stubbing with travel and travel_to. 2013-11-21 17:29:53 +01:00
Jon Leighton
64b9e93bb5 Fix ActiveRecord::Relation#unscope
I'm pretty confused about the addition of this method. The documentation
says that it was intended to allow the removal of values from the
default scope (in contrast to #except). However it behaves exactly the
same as except: https://gist.github.com/jonleighton/7537008 (other than
having a slightly enhanced syntax).

The removal of the default scope is allowed by
94924dc32baf78f13e289172534c2e71c9c8cade, which was not a change we
could make until 4.1 due to the need to deprecate things. However after
that change #unscope still gives us nothing that #except doesn't already
give us.

However there *is* a desire to be able to unscope stuff in a way that
persists across merges, which would allow associations to be defined
which unscope stuff from the default scope of the associated model. E.g.

  has_many :comments, -> { unscope where: :trashed }

So that's what this change implements. I've also corrected the
documentation. I removed the guide references to #except as I think
unscope really supercedes #except now.

While we're here, there's also a potential desire to be able to write
this:

  has_many :comments, -> { unscoped }

However, it doesn't make sense and would not be straightforward to
implement. While with #unscope we're specifying exactly what we want to
be removed from the relation, with "unscoped" we're just saying that we
want it to not have some things which were added earlier on by the
default scope. However in the case of an association, we surely don't
want *all* conditions to be removed, otherwise the above would just
become "SELECT * FROM comments" with no foreign key constraint.

To make the above work, we'd have to somehow tag the relation values
which get added when evaluating the default scope in order to
differentiate them from other relation values. Which is way too much
complexity and therefore not worth it when most use cases can be
satisfied with unscope.

Closes #10643, #11061.
2013-11-20 22:23:16 +00:00
Yves Senn
da800614ca swap arguments for some assert_equal statements => expected, actual 2013-11-20 13:58:09 +01:00
Yves Senn
f83c9b10b4 use arel nodes to represent non-string order_values.
This fixes a bug when merging relations of different classes.

```
Given:
  Post.joins(:author).merge(Author.order(name: :desc)).to_sql

Before:
 SELECT "posts".* FROM "posts"
   INNER JOIN "authors" ON "authors"."id" = "posts"."author_id"
   ORDER BY "posts"."name" DESC

After:
 SELECT "posts".* FROM "posts"
   INNER JOIN "authors" ON "authors"."id" = "posts"."author_id"
   ORDER BY "authors"."name" DESC
```
2013-11-19 17:40:21 +01:00
Rafael Mendonça França
a7afceec3e Revert "Properly require database tasks so we have access to the raised constant"
This reverts commit fbcd46b1a0d255a34d29caa77bbd31c287446333.

This is not needed anymore. See 7280965
2013-11-19 13:08:06 -02:00
Rafael Mendonça França
728096542a Revert "Explicitly exit with status "1" for create and drop failures"
This reverts commit 22f80ae57b26907f662b7fd50a7270a6381e527e.

See
22f80ae57b (commitcomment-4640676)

Conflicts:
	activerecord/CHANGELOG.md
2013-11-19 13:07:28 -02:00
Yasuo Honda
d7c2958a03 Do not count query for all_constraints and all_tab_cols in Oracle 2013-11-18 11:59:36 +09:00
Yasuo Honda
8e3474bede Address test_merging_where_relations failure by adding order("posts.id") 2013-11-18 02:10:56 +09:00
Carlos Antonio da Silva
fbcd46b1a0 Properly require database tasks so we have access to the raised constant
Fix travis failures.
2013-11-17 14:22:24 -02:00
Ivan Antropov
ec09280765 Fix insertion of records for hmt association with scope, fix #3548 2013-11-17 12:20:50 +07:00
Rafael Mendonça França
c069e0fa34 Merge pull request #12918 from versioncontrol/rails-12866
Checks to see if the record contains the foreign_key to set the inverse automatically

Conflicts:
	activerecord/CHANGELOG.md
2013-11-16 18:28:03 -02:00
Edo Balvers
02ca5580bd Checks to see if the record contains the foreign_key to set the inverse automatically 2013-11-16 21:18:02 +01:00
Ryan Davis
456d308f47 Fix bad test order dependency between LoadAllFixturesTest#test_all_there and FoxyFixturesTest#test_ignores_belongs_to_symbols_if_association_and_foreign_key_are_named_the_same 2013-11-16 00:22:05 -08:00
Ryan Davis
8552791779 Fix bad test order dependency between test/cases/validations/i18n_generate_message_validation_test.rb and test/cases/validations/uniqueness_validation_test.rb 2013-11-16 00:12:12 -08:00
Aaron Patterson
d5dbc037c4 test should clean up after themselves 2013-11-15 14:36:15 -08:00
Aaron Patterson
314e2cc05b Merge pull request #12779 from dougbarth/dont_swallow_exceptions_during_transactional_statements_in_mysql
Don't swallow exceptions in transctional statements
2013-11-15 11:29:12 -08:00
Rafael Mendonça França
8c66623627 Merge pull request #12531 from iamvery/database-tasks-exit-status
Explicitly exit with status "1" for create and drop task failures

Conflicts:
	activerecord/CHANGELOG.md
2013-11-15 16:59:29 -02:00
Doug Barth
2b0406cedb Remove tests for not swallowing exceptions.
From PR, @tenderlove would prefer to not maintain these tests.
2013-11-15 10:29:30 -08:00
Kuldeep Aggarwal
a5d588875f added one test case and example for ActiveRecord::Base.to_param method 2013-11-15 20:05:17 +05:30
Carlos Antonio da Silva
6b84de4575 Fix test name [ci skip] 2013-11-14 23:45:30 -02:00
David Heinemeier Hansson
07996ebc50 Revert "Used Yield instead of block.call" -- this causes all of atom_feed_helper_test.rb to fail with "SystemStackError: stack level too deep".
This reverts commit d3a1ce1cdc60d593de1682c5f4e3230c8db9a0fd.
2013-11-14 15:31:27 -08:00
David Heinemeier Hansson
421c81bd18 Fix that eager loading of polymorphic associations did not work with association empty?/any? predicates any more (there is still a problem when select is applied to a relation, or if you try association#exists? -- but its easier to work around) 2013-11-14 14:43:14 -08:00
Javan Makhmali
633100b9e5 Addendum to #12891
* Fix incorrectly named tests
* Restore Object#to_param behavior
* Ensure param is derived from a squished and truncated string
2013-11-14 15:35:53 -05:00
Rafael Mendonça França
84961dc5df Merge pull request #12889 from kuldeepaggarwal/speed_ups
Used Yield instead of block.call
2013-11-14 11:29:28 -08:00
Kuldeep Aggarwal
d3a1ce1cdc Used Yield instead of block.call 2013-11-15 00:53:57 +05:30
Javan Makhmali
547999df25 Add AR::Base.to_param for convenient "pretty" URLs derived from a model's attribute or method. 2013-11-14 13:38:08 -05:00
Rafael Mendonça França
3d2e8cb71c Merge pull request #12772 from dmathieu/no_touching
Add No Touching
2013-11-13 13:37:40 -08:00
Yves Senn
c994e10862 fix weird Emacs auto indentation. [ci skip] 2013-11-13 17:56:44 +01:00
Yves Senn
f081edb1fe tests for merging Relations of different classes. 2013-11-13 17:41:26 +01:00
Yves Senn
742adce211 move Relation#merge tests into separate file. 2013-11-13 17:41:20 +01:00
Akira Matsuda
a99b81e44f Ensure that a column added in a test is being removed after all 2013-11-13 19:21:40 +09:00
Damien Mathieu
b32ba367f5 add #no_touching on ActiveRecord models 2013-11-13 08:42:38 +01:00
dm1try
dbb7ee1bfd Prevent the counter cache from being decremented twice
when destroying a record on a has_many :through association.
:destroy method has own counter_cache callbacks.
2013-11-11 19:53:02 +03:00
Yves Senn
07ae1e9b55 Unifies mysql and mysql2 casting of booleans. 2013-11-11 16:15:00 +01:00
Yves Senn
07790d5832 test cases to describe the MySQL boolean behavior. 2013-11-11 16:09:02 +01:00
Jay Hayes
22f80ae57b Explicitly exit with status "1" for create and drop failures
* A non-zero exit status allows subsequent shell commands to be chained
  together such as: `rake db:reset test:prepare && rspec && cap deploy`
  (if you're feeling brave :)
* Any exceptions raised during the `create` and `drop` tasks are caught
  in order to print a "pretty" message to the user. Unfortunately doing
  so prevents rake from aborting with a non-zero exit status to the shell.
* Therefore we re-raise the exceptions after the "pretty" message and
  re-catch them in the task.
* From the task we explicitly exit with a non-zero status. This method
  was chosen (rather than just letting rake fail from the exception) so
  that the backtrace is suppressed and the output to stderr is
  unchanged.
* Update activerecord CHANGELOG
2013-11-11 07:54:30 -06:00
Akira Matsuda
331c59f47c Do not count "SHOW CREATE TABLE" queries when testing against mysql 2013-11-11 22:06:27 +09:00
Akira Matsuda
3ce9e43bc3 Avoid sorting an Array including objects from different Classes
addresses "ArgumentError: comparison of VerySpecialComment with SpecialComment failed" in ActiveRecord::DelegationRelationTest#test_#sort!_delegation_is_deprecated
2013-11-11 19:53:54 +09:00
Akira Matsuda
48b10134a5 Load test fixtures where data are needed
Without this, some tests here were not actually testing anything.
2013-11-11 19:53:54 +09:00
Yves Senn
f5802708db Merge pull request #12834 from dredozubov/has_one_association_replacement
Fixes problem with replacing has_one association record with itself
2013-11-11 02:26:23 -08:00
Denis Redozubov
3ed5642e69 Fixes problem with replacing has_one association record with itself 2013-11-11 14:19:12 +04:00
Akira Matsuda
9222928dfb A tiny grammatical fix
[ci skip]
2013-11-11 19:14:42 +09:00
Rafael Mendonça França
98cff28d3f Merge pull request #12749 from iantropov/issue_5303
Add test for ActiveRecord::Relation YAML serialization, for #5303 issue
2013-11-10 23:14:23 -02:00
Yves Senn
140c0c8881 use complete Relation API and not only Model.all.merge!. 2013-11-09 22:02:46 +01:00
Arun Agrawal
539ce8b683 Changed message for Model.inspect
(No database connection) sounds not be
able to connect database.

see more #12804
2013-11-09 20:57:09 +01:00
Yves Senn
97f0d9a0dd log bind variables after they were type casted.
The log output used to be confusing in situation where type casting has
"unexpected" effects. For example when finding records with a `String`.

BEFORE:

irb(main):002:0> Event.find("im-no-integer")
D, [2013-11-09T11:10:28.998857 #1706] DEBUG -- :   Event Load (4.5ms)  SELECT "events".* FROM "events" WHERE "events"."id" = $1 LIMIT 1  [["id", "im-no-integer"]]

AFTER:

irb(main):002:0> Event.find("im-no-integer")
D, [2013-11-09T11:10:28.998857 #1706] DEBUG -- :   Event Load (4.5ms)  SELECT "events".* FROM "events" WHERE "events"."id" = $1 LIMIT 1  [["id", 0]]
2013-11-09 11:23:34 +01:00
Rafael Mendonça França
5741a8aae5 Mark broken test as pending
This will avoid the broken window effect in our test suite
2013-11-08 14:19:09 -02:00
Rafael Mendonça França
78bac468e6 Remove more skip 2013-11-08 14:18:54 -02:00
Rafael Mendonça França
bd09afb5fb Don't skip tests if we don't need to.
We can conditional define the tests depending on the adapter or
connection.

Lets keep the skip for fail tests that need to be fixed.
2013-11-08 13:59:07 -02:00
Rashmi Yadav
90377f9674 Warning removed for ruby-head 2013-11-07 22:04:17 +01:00
Yves Senn
aeaf3a9d00 bring back constant to expose the enum mapping as HWIA. 2013-11-06 15:27:33 +01:00
Doug Barth
5d870c9291 Don't swallow exceptions in transctional statements
The MySQL connection adapater swallows all StandardError exceptions,
which includes Mysql::Error and Mysql2::Error. The comment in the
exception clause claims errors thrown here indicate that transactions
aren't supported by the server but that isn't necessarily true. It's
possible the MySQL server has gone away and swallowing a failed commit
may let the application return a successful response when the data has
not been saved. Also, replication libraries like Galera require that the
application handle exceptions thrown at BEGIN/COMMIT.

I'm unable to determine what version of MySQL threw an exception for
transactional statements. I tried as far back as 3.23.49 with InnoDB
disabled but BEGIN & COMMIT statements do not throw an error. If there's
a real case for this logic to continue, we could instead push this
behavior into a configuration setting.

The exception swallowing has been there since the beginning:
db045dbbf60b53dbe013ef25554fd013baf88134
2013-11-05 11:47:08 -08:00
Yves Senn
44406d1e77 store enum mapping using Strings instead of Symbols.
This allows to assign both `String` and `Symbol` values to the enum
without having to call `to_sym`, which is a security problem.
2013-11-05 17:44:08 +01:00
Yves Senn
6c720d18a2 direct enum assignment rasies ArgumentError for unknown values. 2013-11-05 17:44:08 +01:00
Yves Senn
813c8c0751 define enum methods inside a Module to make them overwritable. 2013-11-05 16:45:34 +01:00
Rafael Mendonça França
679902b916 Remove private API test 2013-11-05 13:31:31 -02:00
Aaron Patterson
9f8762f1d5 The enum value constant isn't used, so rm it for now. 2013-11-04 15:55:29 -08:00
Yves Senn
37d4bfbfd9 fix copy & paste test-case naming. [ci skip] 2013-11-04 19:22:53 +01:00
Carlos Antonio da Silva
92c6305954 Respect cache timestamp format when giving timestamps to #cache_key 2013-11-04 13:11:51 -02:00
Ivan Antropov
0c89d316ab Add test for ActiveRecord::Relation YAML serialization, for #5303 issue 2013-11-03 21:35:44 +07:00
David Heinemeier Hansson
c59e902671 Add test verifying that you can only sort ARs of the same type 2013-11-02 20:05:23 -07:00
David Heinemeier Hansson
430b252d3d Revert "ActiveRecord::Base#<=> has been removed. Primary keys may not be in order," -- will be replaced with a check to ensure that the keys used for comparison are integers, and only fail if they are not.
This reverts commit 6256734e2d0bdd89f4b5d11da259d40afa0c95c7.

Conflicts:
	activerecord/CHANGELOG.md
2013-11-02 19:56:58 -07:00
David Heinemeier Hansson
661637e5b6 Delegate #rewhere to all on the class like all other relation methods 2013-11-02 19:45:03 -07:00
David Heinemeier Hansson
0342335473 Merge pull request #12747 from yury/explicit-enum-values
Explicit mapping for enum
2013-11-02 18:29:22 -07:00
Yury Korolev
7caa09c5e1 Explicit mapping for enum 2013-11-02 17:48:16 -07:00
David Heinemeier Hansson
f950b2699f Added ActiveRecord::QueryMethods#rewhere which will overwrite an existing, named where condition. 2013-11-02 17:36:45 -07:00
Rafael Mendonça França
4d7080f80c unscope now works on default_scope after 94924dc32baf78f13e289172534c2e71c9c8cade 2013-11-02 22:11:20 -02:00
David Heinemeier Hansson
09447929a0 Add a test case for the scope enum adds 2013-11-02 16:18:31 -07: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
Carlos Antonio da Silva
a2f27385f6 Use an already existing fixture 2013-11-02 18:13:02 -02:00
Carlos Antonio da Silva
6963e8959f Fix to work on Ruby 1.9.3, example and changelog improvements 2013-11-02 18:08:37 -02:00
David Heinemeier Hansson
db41eb8a6e Added ActiveRecord::Base#enum for declaring enum attributes where the values map to integers in the database, but can be queried by name 2013-11-02 12:01:31 -07:00
Rafael Mendonça França
1918b12c04 Fix wrong behavior where associations with dependent: :destroy options
was using nullify strategy

This caused a regression in applications trying to upgrade.

Also if the user set the dependent option as destroy he expects to get
the records removed from the database.
2013-11-01 19:04:30 -02:00
Rafael Mendonça França
a221b30b3f Test with the right association 2013-11-01 14:26:05 -02:00
Arun Agrawal
c10a78124c More Warnings removed for ruby trunk
Same as 4d4ff531b8807ee88a3fc46875c7e76f613956fb
2013-11-01 13:47:23 +01:00
Arun Agrawal
816126862e Warnings removed for ruby trunk
Same as 4d4ff531b8807ee88a3fc46875c7e76f613956fb
2013-11-01 09:49:57 +01:00
Alan Kennedy
f74a5616e8 Save has_one associations only if record has changes
Prevents save related callbacks such as `after_commit` being
triggered when `has_one` objects are already persisted and have no
changes.
2013-10-31 18:16:29 +00:00