Skip to content
Browse files

Ensure that the foreign key gets set when doing record.create_associa…

…tion or record.create_association. Fixes #1960.
  • Loading branch information...
1 parent 9370855 commit 6d2acc1195f43e44308e59bac11756a833f63ccc @jonleighton jonleighton committed Jul 8, 2011
View
13 activerecord/lib/active_record/associations/singular_association.rb
@@ -18,11 +18,11 @@ def writer(record)
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 @@ def replace(record)
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
View
14 activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -658,4 +658,18 @@ def test_create_bang_with_block
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

0 comments on commit 6d2acc1

Please sign in to comment.
Something went wrong with that request. Please try again.