Permalink
Browse files

Merge pull request #10713 from senny/10693_fix_primary_key_option_on_…

…has_many

Fix the `:primary_key` option for `has_many` associations.
Conflicts:
	activerecord/CHANGELOG.md
	activerecord/lib/active_record/associations/has_many_association.rb
  • Loading branch information...
1 parent f8c4805 commit d29399061e54092fdbf57780c38e19dd1921f45d @rafaelfranca rafaelfranca committed May 23, 2013
@@ -1,5 +1,10 @@
## unreleased ##
+* Fix the `:primary_key` option for `has_many` associations.
+ Fixes #10693.
+
+ *Yves Senn*
+
* fixes bug introduced by #3329. Now, when autosaving associations,
deletions happen before inserts and saves. This prevents a 'duplicate
unique value' database error that would occur if a record being created had
@@ -89,8 +89,7 @@ def delete_records(records, method)
records.each { |r| r.destroy }
update_counter(-records.length) unless inverse_updates_counter_cache?
else
- keys = records.map { |r| r[reflection.association_primary_key] }
- scope = scoped.where(reflection.association_primary_key => keys)
+ scope = self.scope.where(reflection.klass.primary_key => records)
if method == :delete_all
update_counter(-scope.delete_all)
@@ -1492,6 +1492,14 @@ def test_has_many_custom_primary_key
assert_equal david.essays, Essay.find_all_by_writer_id("David")
end
+ def test_has_many_assignment_with_custom_primary_key
+ david = people(:david)
+
+ assert_equal ["A Modest Proposal"], david.essays.map(&:name)
+ david.essays = [Essay.create!(name: "Remote Work" )]
+ assert_equal ["Remote Work"], david.essays.map(&:name)
+ end
+
def test_blank_custom_primary_key_on_new_record_should_not_run_queries
author = Author.new
assert !author.essays.loaded?
@@ -27,6 +27,7 @@ class Person < ActiveRecord::Base
has_many :agents_posts, :through => :agents, :source => :posts
has_many :agents_posts_authors, :through => :agents_posts, :source => :author
+ has_many :essays, primary_key: "first_name", foreign_key: "writer_id"
scope :males, :conditions => { :gender => 'M' }
scope :females, :conditions => { :gender => 'F' }

0 comments on commit d293990

Please sign in to comment.