From 068f092ced8483e557725542dd919ab7c516e567 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Sat, 14 Jun 2014 09:21:31 -0600 Subject: Don't save through records twice If the through record gets created in an `after_create` hook that is defined before the association is defined (therefore after its `after_create` hook) get saved twice. This ensures that the through records are created only once, regardless of the order of the hooks. --- .../has_many_through_associations_test.rb | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 8641584c0c..6895df73c1 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -1139,4 +1139,23 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal 2, post.lazy_readers_unscope_skimmers.to_a.size assert_equal 2, post.lazy_people_unscope_skimmers.to_a.size end + + class ClubWithCallbacks < ActiveRecord::Base + self.table_name = 'clubs' + after_create :add_a_member + + has_many :memberships, inverse_of: :club, foreign_key: :club_id + has_many :members, through: :memberships + + def add_a_member + members << Member.last + end + end + + def test_has_many_with_callback_before_association + Member.create! + club = ClubWithCallbacks.create! + + assert_equal 1, club.reload.memberships.count + end end -- cgit v1.2.3