Created
February 25, 2014 22:49
-
-
Save tenderlove/9219677 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb | |
index 31b8d27..1680951 100644 | |
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb | |
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb | |
@@ -30,17 +30,29 @@ module ActiveRecord | |
unless owner.new_record? | |
records.flatten.each do |record| | |
raise_on_type_mismatch!(record) | |
- record.save! if record.new_record? | |
end | |
end | |
super | |
end | |
+ def concat_records2(records) | |
+ result = true | |
+ | |
+ records.flatten.each do |record| | |
+ raise_on_type_mismatch!(record) | |
+ add_to_target(record) do |rec| | |
+ result &&= insert_record(rec, true, true) unless owner.new_record? | |
+ end | |
+ end | |
+ | |
+ result && records | |
+ end | |
+ | |
def concat_records(records) | |
ensure_not_nested | |
- records = super | |
+ records = concat_records2(records) | |
if owner.new_record? && records | |
records.flatten.each do |record| | |
diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb | |
index 2d0d454..e555c52 100644 | |
--- a/activerecord/test/cases/associations/callbacks_test.rb | |
+++ b/activerecord/test/cases/associations/callbacks_test.rb | |
@@ -101,6 +101,27 @@ class AssociationCallbacksTest < ActiveRecord::TestCase | |
"after_adding#{david.id}"], ar.developers_log | |
end | |
+ def test_has_and_belongs_to_many_before_add_called_before_save | |
+ dev = nil | |
+ new_dev = nil | |
+ klass = Class.new(Project) do | |
+ def self.name; Project.name; end | |
+ has_and_belongs_to_many :developers_with_callbacks, | |
+ :class_name => "Developer", | |
+ :before_add => lambda { |o,r| | |
+ dev = r | |
+ new_dev = r.new_record? | |
+ } | |
+ end | |
+ rec = klass.create! | |
+ alice = Developer.new(:name => 'alice') | |
+ rec.developers_with_callbacks << alice | |
+ assert_equal alice, dev | |
+ assert_not_nil new_dev | |
+ assert new_dev, "record should not have been saved" | |
+ assert_not alice.new_record? | |
+ end | |
+ | |
def test_has_and_belongs_to_many_after_add_called_after_save | |
ar = projects(:active_record) | |
assert ar.developers_log.empty? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment