I'm using Ruby 1.9.3 and RoR 3.20.
I am looking for a way to insert into two different tables, the parent and then child tables, in a single commit.
Currently, ActiveRecord generates code like this:
(0.0ms) BEGIN
SQL (1.0ms) INSERT INTO `parent` (`datefield`) VALUES ('2015-03-12 13:23:22')
(81.0ms) COMMIT
(1.0ms) BEGIN
SQL (1.0ms) INSERT INTO `child` ( `parent_id`, `textfield`) VALUES ('1', 'text')
(73.0ms) COMMIT
and the ruby code that causes this is:
fo = Parent.create!(datefield: '2015-03-12 13:23:22')
fo.child.create(textfield: 'text')
I use create! so that if it fails it will bail out and won't try to create the record for the child table which will then also fail because of foreign key constraints, but I would prefer that this interaction be handled by a database transaction.
I looked at this thread which has relevant info posted in the answer and comments but I'm hoping something has changed in the past few years since that question was asked? link Any assistance is appreciated.