Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Revert "Revert "Merge pull request #10901 from armstrjare/fix_query_n…

…ull_foreign_key_on_new_record_collection_ids_reader""

This reverts commit 5009b07.

Also updated the CHANGELOG and adjusted the test-case to match the one on master.
  • Loading branch information...
commit 27b38838467cf47f83caefbddcdb96aceca052ee 1 parent b0c6597
@senny senny authored
View
15 activerecord/CHANGELOG.md
@@ -4,6 +4,21 @@
*Yves Senn*
+* Fixes bug where `Company.new.contract_ids` would incorrectly load
+ all non-associated contracts.
+
+ Example:
+
+ company = Company.new # Company has many :contracts
+
+ # before
+ company.contract_ids # => SELECT ... WHERE `contracts`.`company_id` IS NULL
+
+ # after
+ company.contract_ids # => []
+
+ *Jared Armstrong*
+
* Fix the `:primary_key` option for `has_many` associations.
Fixes #10693.
View
2  activerecord/lib/active_record/associations/collection_association.rb
@@ -43,7 +43,7 @@ def writer(records)
# Implements the ids reader method, e.g. foo.item_ids for Foo.has_many :items
def ids_reader
- if loaded? || options[:finder_sql]
+ if owner.new_record? || loaded? || options[:finder_sql]
load_target.map do |record|
record.send(reflection.association_primary_key)
end
View
27 activerecord/test/cases/associations/has_many_associations_test.rb
@@ -1311,6 +1311,33 @@ def test_get_ids_for_unloaded_associations_does_not_load_them
assert !company.clients.loaded?
end
+ def test_get_ids_for_association_on_new_record_does_not_try_to_find_records
+ Company.columns # Load schema information so we don't query below
+ Contract.columns # if running just this test.
+
+ company = Company.new
+ assert_queries(0) do
+ company.contract_ids
+ end
+
+ assert_equal [], company.contract_ids
+ end
+
+ def test_set_ids_for_association_on_new_record_applies_association_correctly
+ contract_a = Contract.create!
+ contract_b = Contract.create!
+ Contract.create! # another contract
+ company = Company.new(:name => "Some Company")
+
+ company.contract_ids = [contract_a.id, contract_b.id]
+ assert_equal [contract_a.id, contract_b.id], company.contract_ids
+ assert_equal [contract_a, contract_b], company.contracts
+
+ company.save!
+ assert_equal company, contract_a.reload.company
+ assert_equal company, contract_b.reload.company
+ end
+
def test_get_ids_ignores_include_option
assert_equal [readers(:michael_welcome).id], posts(:welcome).readers_with_person_ids
end
Please sign in to comment.
Something went wrong with that request. Please try again.