Skip to content

Commit ad7169b

Browse files
committed
Add set_new_record to singular create associations
Fixes an issue where the foreign key wasn't being set, causing validation to fail. Eg: ```ruby require "bundler/inline" gemfile(true) do source "https://rubygems.org" git_source(:github) { |repo| "https://github.com/#{repo}.git" } gem "rails", github: "rails/rails", branch: "main" gem "sqlite3" end require "active_record" require "minitest/autorun" require "logger" ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Schema.define do create_table :posts, force: true do |t| end create_table :comments, force: true do |t| t.integer :post_id end end class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post validates_presence_of :post_id def create_with_post new_post = create_post save end end class BugTest < Minitest::Test def test_association_stuff comment = Comment.new comment.create_with_post assert_predicate comment.post, :persisted? assert_equal Post.last, comment.post assert_predicate comment, :valid? # Failure: # BugTest#test_association_stuff [repro_fk_validation_change.rb:53]: # Expected #<Comment id: nil, post_id: nil> to be valid?. assert_predicate comment, :persisted? end end ```
1 parent 40255e4 commit ad7169b

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

activerecord/lib/active_record/associations/singular_association.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ def _create_record(attributes, raise_error = false, &block)
5757
reflection.klass.transaction do
5858
record = build(attributes, &block)
5959
saved = record.save
60+
set_new_record(record)
6061
raise RecordInvalid.new(record) if !saved && raise_error
6162
record
6263
end

activerecord/test/cases/associations/belongs_to_associations_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1443,6 +1443,15 @@ def test_should_set_foreign_key_on_create_association!
14431443
assert_equal firm.id, client.client_of
14441444
end
14451445

1446+
def test_should_set_foreign_key_on_create_association_with_unpersisted_owner
1447+
tagging = Tagging.new
1448+
tag = tagging.create_tag
1449+
1450+
assert_not_predicate tagging, :persisted?
1451+
assert_predicate tag, :persisted?
1452+
assert_equal tag.id, tagging.tag_id
1453+
end
1454+
14461455
def test_should_set_foreign_key_on_save
14471456
client = Client.create! name: "fuu"
14481457
firm = client.build_firm name: "baa"

0 commit comments

Comments
 (0)