From dfec3737b05d22e6f298bcae0a8948a4b8803ebd Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 8 Jul 2011 20:59:25 +0100 Subject: Ensure that the foreign key gets set when doing record.create_association or record.create_association. Fixes #1960. --- .../lib/active_record/associations/singular_association.rb | 13 +++++++++++-- .../cases/associations/belongs_to_associations_test.rb | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index 6b010064d5..a1a921bcb4 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -18,11 +18,11 @@ module ActiveRecord end def create(attributes = {}, options = {}, &block) - build(attributes, options, &block).tap { |record| record.save } + create_record(attributes, options, &block) end def create!(attributes = {}, options = {}, &block) - build(attributes, options, &block).tap { |record| record.save! } + create_record(attributes, options, true, &block) end def build(attributes = {}, options = {}) @@ -50,6 +50,15 @@ module ActiveRecord def set_new_record(record) replace(record) end + + def create_record(attributes, options, raise_error = false) + record = build_record(attributes, options) + yield(record) if block_given? + saved = record.save + set_new_record(record) + raise RecordInvalid.new(record) if !saved && raise_error + record + end end end end diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 7338513b41..4190f6d76d 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -667,4 +667,18 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase firm = client.create_firm!{ |f| f.name = 'Agency Company' } assert_equal 'Agency Company', firm.name end + + def test_should_set_foreign_key_on_create_association + client = Client.create! :name => "fuu" + + firm = client.create_firm :name => "baa" + assert_equal firm.id, client.client_of + end + + def test_should_set_foreign_key_on_create_association! + client = Client.create! :name => "fuu" + + firm = client.create_firm! :name => "baa" + assert_equal firm.id, client.client_of + end end -- cgit v1.2.3