@@ -26,15 +26,15 @@ def create!(form_id:,
2626 guidance_markdown :,
2727 answer_type :,
2828 )
29- save_to_database !( page )
29+ update_and_save_to_database !( page )
3030 page
3131 end
3232
3333 def save! ( record )
3434 page = Api ::V1 ::PageResource . new ( record . attributes , true )
3535 page . prefix_options = record . prefix_options
3636 page . save!
37- save_to_database !( page )
37+ update_and_save_to_database !( page )
3838 page
3939 end
4040
@@ -44,7 +44,7 @@ def destroy(record)
4444
4545 begin
4646 page . destroy # rubocop:disable Rails/SaveBang
47- Page . destroy ( record . id )
47+ Page . find ( record . id ) . destroy_and_update_form!
4848 rescue ActiveResource ::ResourceNotFound , ActiveRecord ::RecordNotFound
4949 # ActiveRecord::Persistence#destroy doesn't raise an error
5050 # if record has already been destroyed, let's emulate that
@@ -58,7 +58,7 @@ def move_page(record, direction)
5858 page . prefix_options = record . prefix_options
5959
6060 page . move_page ( direction )
61- save_to_database !( page )
61+ update_and_save_to_database !( page )
6262
6363 page
6464 end
@@ -101,5 +101,27 @@ def save_to_database!(record)
101101
102102 save_routing_conditions_to_database! ( record )
103103 end
104+
105+ def update_and_save_to_database! ( record )
106+ attributes = record . database_attributes
107+
108+ begin
109+ # transaction is required to be able to retry after catching exception
110+ ActiveRecord ::Base . transaction do
111+ page = Page . find_or_initialize_by ( id : record . id )
112+ page . assign_attributes ( **attributes )
113+ page . save_and_update_form
114+ end
115+ # we get an exception if the form does not already exist in the database
116+ rescue ActiveRecord ::RecordInvalid => e
117+ raise unless e . message . include? "Form must exist"
118+
119+ find_form_and_save_to_database! ( record )
120+
121+ retry
122+ end
123+
124+ save_routing_conditions_to_database! ( record )
125+ end
104126 end
105127end
0 commit comments