Skip to content

Instantly share code, notes, and snippets.

@rskelley9
Last active October 31, 2016 05:43
Show Gist options
  • Save rskelley9/d44fc002fc0a923ec2639f42afa0d4ae to your computer and use it in GitHub Desktop.
Save rskelley9/d44fc002fc0a923ec2639f42afa0d4ae to your computer and use it in GitHub Desktop.
How I remedied duplicate form submissions: https://www.tumblr.com/blog/ryankelley
class ApplicationController < ActionController::Base …
private
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
class PuppiesController < ApplicationController
before_filter :redirect_if_existing, only: [:new]
after_filter :browser_will_not_cache_response, only: [:new]
def create
@puppy =
Puppy.
by_user_from_this_year(current_user.id).
first_or_initialize(params[:puppie])
## 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 redirect_if_existing
## If user already has a record in the puppies table
## created this year
## then redirect them to edit that Puppy.
if Puppy.by_user_from_this_year(current_user.id).any?
flash[:notice] =
"You may only create one puppy per year. You may edit your existing puppy."
redirect_to edit_puppy_path(@puppy)
end
end
end
@rskelley9
Copy link
Author

I created this as an anonymous user at first, annoyingly enough:
original

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment