0

I have a controller that looks like this:

  def new
    @title = "Add New Post"
    @post = Post.new
  end

  def create
    @title = "Add New Post"
    @post = Post.new(params[:post])
    if @post.save
      flash[:success] = @post.name+" successfully added. Thank you!"
      redirect_to @post
    else
      render 'new'
    end
  end

The problem is that if a user successfully creates a new post, then decides to change something by pressing the Back button and hitting "Save" again, I get duplicate entries.

What is the best way to prevent something like this? I thought that the create action is automatically a POST request in Rails, so the browser should say something like "Are you sure you want to resend the data, bla bla bla..."

Running rake routes does show this:

            POST   /posts(.:format)                                     posts#create
new_post    GET    /posts/new(.:format)                                 posts#new
4

1 回答 1

2

Just a direction to think about - when you get a request to create a new Post you may check if a Post with the same title for example exists for the current user. But only the fact that the Post with the same title exists doesn't mean that you should update it. Here you should decide how to determine if a Post needs to be updated or saved. One of possible solutions would be to compare a time of request and an existing Post's created_at or updated_at time (for example you may update posts created within the last hour).

Another way (seems to be a better one than the previous) may be to add a field and a property to database table posts and a model Post respectively which would store an unique identifier (some hash for example) for a Post (not an id for sure as a Post doesn't yet exist at the moment, it could be for example a hashed timestamp). Then you'd add to your form a hidden input field and set it's value to that unique identifier. This way when a user hits a Back button he goes to form with that identifier already set for existing Post and now after he submits the form the second time you are able to find a Post by that unique identifier and update it.

于 2013-06-14T09:30:01.180 回答