Rails 3 - Before form submission human check

2019-09-02 00:52发布

问题:

I've got a simple message form (:name, :title, :body) that has a recaptcha. When I have both my form and recaptcha on the same page I don't get the same user experience because my server-side form model validations don't work like i'd like them to. So I was thinking of implementing a redirect to a seperate recaptcha page before the form attributes get saved into my database.

I was wondering what are the best practices for this situation? Should I send a session of the message attributes to another controller that handles the recaptcha? If that's the case, I'm a bit lost on how to go about that. Any ideas?

回答1:

Another way to do it is to create an additional model attribute, an integer with a name like submission_step, with values corresponding to what step the user got to in the submission process. In this case there are only two:

0: before recaptcha
1: after successful recaptcha

So when the user first submits the form, a new message is instantiated with a submission_step of 0, validations are run and assuming they pass the "uncaptcha'd" message is created. The user is then sent the recaptcha page. If they do the recaptcha successfully, the record is updated to change the submission_step attribute to a 1.

You can then use submission_step as a scope to filter for forms that have passed the recaptcha step. You can also validate based on the step using :if or :unless conditional options in validate.

Of course this creates records in the database for forms that have not passed the recaptcha step, which might be a problem -- although you could periodically clean them out. But I've found it's a fairly clean solution and makes it easy if you want to add additional steps to the process in the future.