0

I have an issue where I have a form that creates an entity, let's say a survey. After submitting the form, the user is taken to an Edit form for the same entity, with more fields.

Some users press the BACK button, and end up resubmitting the same survey twice.

What's a good way to prevent this from happening?

Do I have to generate some kind of UID when the New form is generated, and then save that along with the survey. Then, if users hit back, the same UID will already be present in the form, and I can detect it.

Are there more straightforward solutions that don't require me to store a new piece of information on surveys?

Robin
  • 21,667
  • 10
  • 62
  • 85

1 Answers1

0

You can use scoped validations on entity attributes, eg if a Survey would have_many Questions, they create some questions but then go Back and resubmit they would get validation errors as the questions already exist.

class Question < ApplicationRecord
  belongs_to :survey
  validates_uniqueness_of :name, scope: [ :survey_id ]
end

Of course this won't help much if they change the name of the question, like for instance if they forgot to add a question mark at the end... the validation will pass. For such instances you can have a custom validator:

class Question < ApplicationRecord
  belongs_to :survey
  validate no_similar_question

  def no_similar_question
    errors.add(:name, "You have already created a similar question in this survey!") if survey.questions.where("name like ?", "%#{name}%").count > 1
    # 
  end
end

When that fails you can either just warn them "Question already created" or redirect them to edit the original input, maybe they just realized they made a mistake or want to double check before moving on. Helps improve the UX.

Nick M
  • 2,424
  • 5
  • 34
  • 57
  • 1
    Thanks. I know it's very easy when you have fields that are supposed to be unique. That's not the case for me. I used a token that I store on the entity, this way I can check if it's already been created. There are other ways to do it, with cookies and JS but I went with this one. – Robin Jul 12 '19 at 20:41