belongs_to does not set foreign key depending object save order
artworx opened this issue · 0 comments
artworx commented
Reproduced using the specs in spec/model/model_spec.cr
1, if User is saved after belogs_to is assigned it triggers an exception
temporary do
reinit
u = User.new({first_name: "John"})
post = Post.new({user: u, title: "some post" })
u.save!
post.save! # Exception
post.user_id.should eq(u.id)
end
This fails with null value in column "user_id" violates not-null constraint
, the SQL is
INSERT INTO "model_users" ("first_name", "updated_at", "created_at") VALUES ('John', '2020-03-20 11:27:14.096 +00:00', '2020-03-20 11:27:14.096 +00:00') RETURNING *
INSERT INTO "model_posts" ("title") VALUES ('some post') RETURNING *
2, it works when only Post is saved
temporary do
reinit
u = User.new({first_name: "John"})
post = Post.new({user: u, title: "some post" })
post.save!
post.user_id.should eq(u.id) # true
end
INSERT INTO "model_users" ("first_name", "updated_at", "created_at") VALUES ('John', '2020-03-20 11:27:13.991 +00:00', '2020-03-20 11:27:13.991 +00:00') RETURNING *
INSERT INTO "model_posts" ("title", "user_id") VALUES ('some post', 1) RETURNING *
3, it works when User is saved before getting assigned to Post
temporary do
reinit
u = User.new({first_name: "John"})
u.save!
post = Post.new({user: u, title: "some post" })
post.save!
post.user_id.should eq(u.id)
end
INSERT INTO "model_users" ("first_name", "updated_at", "created_at") VALUES ('John', '2020-03-20 11:27:13.991 +00:00', '2020-03-20 11:27:13.991 +00:00') RETURNING *
INSERT INTO "model_posts" ("title", "user_id") VALUES ('some post', 1) RETURNING *