From 0da426be96d9e02b1b7a34e364dff984cd4218f3 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 18 Aug 2006 07:35:07 +0000 Subject: Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4786 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activerecord/test/associations_join_model_test.rb | 24 ++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/associations_join_model_test.rb b/activerecord/test/associations_join_model_test.rb index b5d48db8bc..508628f37a 100644 --- a/activerecord/test/associations_join_model_test.rb +++ b/activerecord/test/associations_join_model_test.rb @@ -363,14 +363,24 @@ class AssociationsJoinModelTest < Test::Unit::TestCase assert_nil posts(:thinking).tags.find_by_name("General").attributes["tag_id"] end - def test_raise_error_when_adding_to_has_many_through - assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags << tags(:general) } - assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.push tags(:general) } - assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.concat tags(:general) } - assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.build(:name => 'foo') } - assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.create(:name => 'foo') } + def test_raise_error_when_adding_new_record_to_has_many_through + assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags << tags(:general).clone } + assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).clone.tags << tags(:general) } + assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags.build } end - + + def test_create_associate_when_adding_to_has_many_through + count = Tagging.count + assert_nothing_raised { posts(:thinking).tags << tags(:general) } + assert_equal(count + 1, Tagging.count) + + assert_nothing_raised { posts(:thinking).tags.create!(:name => 'foo') } + assert_equal(count + 2, Tagging.count) + + assert_nothing_raised { posts(:thinking).tags.concat(Tag.create!(:name => 'abc'), Tag.create!(:name => 'def')) } + assert_equal(count + 4, Tagging.count) + end + def test_has_many_through_sum_uses_calculations assert_nothing_raised { authors(:david).comments.sum(:post_id) } end -- cgit v1.2.3