From 761283ffdb5750f8a38e2ed67891d2b2b9152d7f Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 8 Aug 2009 21:51:33 +0100 Subject: Ensure hm:t#create/create! throws ActiveRecord::RecordNotSaved when the owner is new --- .../lib/active_record/associations/has_many_through_association.rb | 4 ++++ .../test/cases/associations/has_many_through_associations_test.rb | 7 +++++++ 2 files changed, 11 insertions(+) (limited to 'activerecord') 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 e21ef90391..ed7c3a6e08 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -8,6 +8,8 @@ module ActiveRecord alias_method :new, :build def create!(attrs = nil) + ensure_owner_is_not_new + transaction do self << (object = attrs ? @reflection.klass.send(:with_scope, :create => attrs) { @reflection.create_association! } : @reflection.create_association!) object @@ -15,6 +17,8 @@ module ActiveRecord end def create(attrs = nil) + ensure_owner_is_not_new + transaction do self << (object = attrs ? @reflection.klass.send(:with_scope, :create => attrs) { @reflection.create_association } : @reflection.create_association) object 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 8529ff0285..f6b4a42377 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -169,6 +169,13 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal peeps + 1, posts(:thinking).people.count end + def test_create_on_new_record + p = Post.new + + assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(:first_name => "mew") } + assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(:first_name => "snow") } + end + def test_clear_associations assert_queries(2) { posts(:welcome);posts(:welcome).people(true) } -- cgit v1.2.3