In rails controllers, how to prevent double submit (when user double-clic submit button or hit enter twice)?

后端 未结 8 2304
天命终不由人
天命终不由人 2021-02-19 09:50

Well, everything\'s in the title but I\'ll explain a little more :-)

My rails app contain many forms (Ajaxified or not).

To prevent users to submit twice or more

8条回答
  •  情深已故
    2021-02-19 09:55

    Here's what I'd do:

    1. Add a "token" field to an object in db that's about to be changed.
    2. Put that token into a form that modifies said object.
    3. Right after modification save that object with NEW token.
    4. Use that token in other page views.

    This will not prevent double submission, but at least will prevent the changes from second commit. I.e. when user submits the form second time the code will check the submitted token against the one in database and if they do not match - do not do an update to the object.

    This also has a draw back for newly created objects (i.e. if user want's to create a comment or smth like that). But in this case you may want to check the creation time interval from same user and if it's less than, say, 5 seconds - you'd prevent the object from being "created".

提交回复
热议问题