Rails: Prevent duplicate inserts due to pressing back button and save again

Think about a simple Rails scaffold application with a "new" action containing a form to add records to a database with a "save" button. After the "create" action the controller redirects to the "show" action, where the user can use the "edit" link to edit the just inserted record. So far, so simple.

But if the user instead uses the browser's back button after creating a record to get back to the "new" action, the browser shows the form with the values the user just has entered. Now he changes some values and presses "save" again. He thinks that this would change the record, but of course this creates a new record.

What is the preferred way to prevent such duplicate entries? I'm looking for a general solution, maybe based on cookies or JavaScript.


After some investigations I found a suitable solution based on cookies. Here it is:

In the controller's "new" action, a timestamp with the current time is generated and rendered in the form as hidden field. When the user submits the form, this timestamps gets back to the controller's "create" action. After creating the record, this timestamp is stored in the session cookie. If the user goes back to the "new" form via browser's back button, he gets a stale form, which means its timestamp is older than the one stored in the cookie. This is checked before creating the record and results in an error message.

Here is the controller code:

def new
@post = Post.new
@stale_form_check_timestamp = Time.now.to_i

def create
@post = Post.new(params[:post])

if session[:last_created_at].to_i > params[:timestamp].to_i
flash[:error] = 'This form is stale!'
render 'new'
@stale_form_check_timestamp = Time.now.to_i
session[:last_created_at] = @stale_form_check_timestamp

And here the form code:

- form_for @post do |f|
= tag :input, :type => 'hidden', :name => 'timestamp', :value => @stale_form_check_timestamp
= f.input :some_field
= .......

When I had that same problem I created this little gem that solves it. When the user hits back, he's redirected to the edit_path of the record, instead of going back to the new_path.


You can do something like:

def create
@user = User.new(params[:user])
if result = @user.save
redirect_on_back_to edit_user_path(@user) # If user hits 'back' he'll be redirected to edit_user_path
redirect_to @user

Your model validations will ensure things like email addresses are unique, but I think this is more about usability and experience than anything else.

Say you are talking about an account creation form. First of all, your form submit button should say something like "Create Account", instead of just "Submit". Then depending on whether it was successful or not, show a message like either "Account successfully created" or "There were errors creating your account". If the user sees this message, they will know what happened.

Sure you can't prevent someone from hitting the back button and hitting enter again, but you should design for the majority of use cases. If they happen to hit back, they will see the button that says "Create Account". You should probably have some other text on the page that says "Please sign up for a new account to get started".

Just my $0.02.

You can use validators to make sure that no duplicate values are inserted. In this case validates_uniqueness_of :field

If you for example want to prevent users from having the same email address you could put the following code in your user model.

validates_uniqueness_of :email

This checks the column for any previous entries that are the same as the one your trying to inert. Good luck

Session or cookie may result in sides effects.

I totally agree : if there is a way to validate with your model, it's the safest way to prevent duplicate records.

Still you can do 2 things. Prevent browser caching : fields will appear empty in the form when the user clicks on the back button. And disable the "Create" button when clicked.

= f.submit "Create", :disable_with => "Processing..."

When your user will press the back button the button will be disabled.

Category:ruby on rails Time:2011-01-11 Views:1

Related post

  • How to use SqlBulkCopy to prevent duplicates insert? 2012-03-29

    I am going to use SqlBulkCopy, but I need to prevent duplicates insert. What is the best way to do it? Have I do check existence for each item before make execute WriteToServer command? --------------Solutions------------- Bring all the values form t

  • Rails preventing duplicates in polymorphic has_many :through associations 2010-05-22

    Is there an easy or at least elegant way to prevent duplicate entries in polymorphic has_many through associations? I've got two models, stories and links that can be tagged. I'm making a conscious decision to not use a plugin here. I want to actuall

  • Prevent duplicate insert without session 2011-01-31

    im working on sharepoint 2010 (using visual webpart) is there any way to prevent duplicate insert in a list when page is refreshed using F5, without using session thx --------------Solutions------------- The sharepoint "way" is usually to redirect to

  • Prevent duplicate inserts without using unique keys in Oracle 2011-11-08

    This is a use case in member enrollment via web application/web service. We have a complex algorithm for checking if a member is duplicate, by looking at multiple tables like phone,address etc. The algorithm varies based on member's country. So this

  • Rails, Cucumber, Capybara - Cucumber step cannot press a button 2012-01-09

    Running the latest builds of Rails, Cucumber and Capybara I am getting stuck when Capybara needs to press a button. I have tried to eliminate all issues and have made sure that the form is generated and displayed correctly. I am getting 2 errors: A)

  • Preventing Duplicate Inserts Into SQL With PHP 2008-11-09

    I'm going to running thousands of queries into SQL and I need to prevent the duplication of field 'domain'. Never had to do this before and any help would be appreciated. --------------Solutions------------- You probably want to create a "UNIQUE" con

  • Rails: Prevent duplicate entry from simultaneous submission 2011-09-09

    We're having a problem with our app allowing people to sign up multiple times with the same account information (email, specifically). Our user model validates the uniqueness of the email parameter, and we are also using some javascript to make sure

  • prevent duplicate insert by using updatepanel 2011-01-14

    i wrote a page which are several fields and there is gridview which keeps the data inserted bottom of the page and i added a updatepanel... when i click the insert double data inserting to grid how to prevent it... --------------Solutions------------

  • can isolation levels prevent duplicate insert? 2012-04-09

    i have a table like this UserPageId (Primary Key) int UserId (user Foreign Key) int PageId (page Foreign Key) int and the whole senario is to prevent user to add one page more than once,,according to each user can be use with several person and we mi

  • Preventing Duplicate Table Inserts 2011-06-17

    The database is SQL Server 2008. I have a query which extracts rows from one or more tables and then attempts to insert them into a table variable. I'd like an efficent way to prevent duplicate inserts, so what I came up with was: INSERT INTO @MyTabl

  • preventing duplicate table inserts using jdo in android connected appengine 2012-03-18

    I would like to know how to prevent duplicate inserts when doing an RPC call from an Android client connected to app engine. Below is my code and what I tried at the back-end but when I do this I get an "Internal Server Error". public void createenti

  • Prevent duplicate record insert on manual page refresh 2010-09-16

    I have a problem which has only just surfaced itself. I'm working in a MVC environment. The method names in my interface class match those of the request module and action i.e. ?module=test&action=action would result in a method called public fun

  • Preventing duplicate records across multiple connections using Rails 2011-01-13

    I have two separate processes, each with it's own database connection, inserting product records into a table. Before a process inserts a product into the table, it checks to see if a product with the same properties already exists. If the product al

  • How to prevent duplicate rows in insert query using Oracle? 2009-10-31

    I have table A in Oracle that has a primary key (id). I need to insert data into this table. How do I prevent duplicate rows? --------------Solutions------------- If the id column is marked as the PK you will not be able to insert a duplicate key, th

  • How to prevent duplicate records being inserted with SqlBulkCopy when there is no primary key 2010-04-07

    I receive a daily XML file that contains thousands of records, each being a business transaction that I need to store in an internal database for use in reporting and billing. I was under the impression that each day's file contained only unique reco

  • Prevent Duplicate Entries and alert via a alert box if user insert duplicate entry 2010-07-09

    How i Prevent Duplicate Entries in database at the time of form submit and display an alert box and stop form submission if entry is duplicate. --------------Solutions------------- You can add a validates_uniqueness_of validation to your model: class

  • Rails - Help with rake task - How to prevent duplicates 2011-02-15

    How to prevent duplicates in rake task ? I have tried to write something but are totally blank. I want to check if the coloum Date matches the date today if that is true then just update the coloum with the scraped data unless create a new row with t

  • How to prevent duplicate values from inserting mySQL considering two columns? 2011-10-20

    Here is my table: Table Name: UserLinks Link_ID User_1 User_2 1 234325 100982 2 116727 299011 3 399082 197983 4 664323 272351 Basically, in this table a duplicate value is: Link_ID User_1 User_2 1 232 109 2 109 232 I have looked around and found that

  • Insert Query (that prevents duplicates) 2014-09-07

    I saw a question similar to mine and I tried to modify the code but to no avail. I have a multiple-field index but it doesn't seem to be stopping duplicates from being imported or entered. I will post here the fields in the index as well as the code

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.263 (s). 13 q(s)