0

I have Table1 who has a has_many relationship with Table2

# app/models/table1.rb
class Table1 < ApplicationRecord
     .
     .
     .
  has_many :table2_relations, class_name: Table2, foreign_key: instance2_id

The belongs_to relationship in Table2 is marked as required:

# app/models/table2.rb
class Table2 < ApplicationRecord
     .
     .
     .
  belongs_to instance2, class_name: Table1, required: true

My ActiveAdmin file is :

ActiveAdmin.register Table1 do
  .
  .
  .
  controller do
    def create
       .
       .
       .
    end

I have an ActiveAdmin page to create a new Table1 that also include table2_relations but since belongs_to required is true, when super is called, it will do all insert statements first then commit, causing a instance2 does not exist error because the creation of Table1 has not commited yet before creation of table2_relations is committed. The creation of table2_relations is only possible in the context of updating. How can I make the creation of Table1 committed first before creation of table2_relations? Thank you

nanakondor
  • 615
  • 11
  • 25

2 Answers2

0

See the heading 'Nested Resources' on the below link:

Link: https://activeadmin.info/5-forms.html

Try to create nested form. This will solve the problem.

Pragya Sriharsh
  • 529
  • 3
  • 6
0

I have been doing Nested Resources just like what Pragya said, but it won't work. then I find out that I have to add inverse_of: :instance2 in Table1 just like this answer: ActiveAdmin has_many form not saved if parent model is new and is NOT NULL in child model

nanakondor
  • 615
  • 11
  • 25