0

I am building a survey-like rails application. The survey has several particular sections (several views) and in each section there are multiple questions. The user will answer those question (free text) and at the bottom of every section view there should be one submit button that saves all entries.

The model for the user answers is:

user_answers(id:integer, user_answer:string, user_project_id:integer, question_id:integer).

The user_answers have a user_project_id to associate it with their created project and a question_id for a an answer. That way the answers later can be directly associated to the right user project and the corresponding question.

What is best practice to save multiple entries/form_for :user_answers with one submit button at the end of the page?

  1. I read about the javascript method Submit two forms with one button, but I fear if the entries are not saved asynchronously it could lead to errors

  2. Sidekiq could be used to do the jobs asynchronously in the background.

Are there maybe other easier ways to do it?

Thank you in advance!

Maxeezy
  • 39
  • 1
  • 6

1 Answers1

0

I actually found out that both are not applicable and the answer to my question was server-side rendering with fields_for. Before I explain fields_for I want to answer why my strategies from above are not relevant.

  1. Submit two forms with one button works, but renders everything client-side. That means it worked on my local machine, but as soon as I deployed the app on heroku and tried it, the javascript would not save all the records because the browser would terminate the JS after the first (or the first few) submit() actions.

  2. is just a service to outsource workload. That would not solve the problem of inconsistent database records.

So I needed to find a way to process the records server-side, and that is fields_for: https://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for.

It allows you to save multiple nested objects by putting it into a "parent"-form_for.

Here is a good tutorial to get a look and feel: https://www.youtube.com/watch?v=PYYwjTlcoa4

In my case, I made a "shell" form_for as a container around the fields_for. The fields_for in my code were dynamically generated according to the number of questions in the database. By submitting the shell form_for, I was able to process all fields_for answers to my survey server-side with one click.

Maxeezy
  • 39
  • 1
  • 6