Last active
October 31, 2016 05:02
-
-
Save rskelley9/6667a222b437edcd41f31094268d06e8 to your computer and use it in GitHub Desktop.
How I remedied duplicate form submissions via preventing cache, and preventing duplicate data save in database in controller layer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
prepend_before_filter :authenticate_user! | |
private | |
## Tell client not to cache the response | |
def client_will_not_cache_response | |
response.headers["Cache-Control”] = “no-cache, no-store” | |
response.headers[“Pragma”] = “no-cache” | |
response.headers[“Expires”] = “Fri, 01 Jan 1990 00:00:00 GMT” | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PuppiesController < ApplicationController | |
before_filter :load_puppy, | |
only: [:new, :create, :show, :update, :edit, :delete] | |
after_filter :browser_will_not_cache_response, only: [:new] | |
def new | |
## If user already has a record in the puppies table | |
## created this year | |
## then redirect them to edit that Puppy. | |
if [email protected]_record? | |
flash[:notice] = "You may only create one puppy per year. You may edit your existing puppy." | |
redirect_to edit_puppy_path(@puppy) and return | |
end | |
end | |
def create | |
## prevent malicious user from setting the user_id | |
@puppy.user_id = current_user.id | |
if @puppy.errors.empty? && @puppy.save | |
redirect_to show_puppy_path(@puppy) | |
else | |
## Tell user they need to fix their mistakes | |
render :edit | |
end | |
end | |
private | |
def load_puppy | |
@puppy = | |
Puppy. | |
includes(:user). | |
by_user_from_this_year(current_user.id). | |
first_or_initialize(params[:puppy]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Rails: How to Prevent Submitting Duplicate Forms
How to Prevent Submitting Duplicate Forms PT. II