扶手:prevent重复插入由于pressing后退按钮,并再次保存 [英] Rails: Prevent duplicate inserts due to pressing back button and save again

查看:130
本文介绍了扶手:prevent重复插入由于pressing后退按钮,并再次保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想想一个简单的Rails脚手架含有一种形式记载了保存按钮添加到数据库中的新操作的应用程序。 创建行动后,控制器重定向到秀操作,即用户可以使用编辑链接来编辑刚刚插入的记录。到目前为止,就这么简单。

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.

但是,如果用户创建记录,回到新动作之后,而不是使用浏览器的后退按钮,浏览器显示了用户刚刚已经进入了价值形式。现在,他再次改变保存的一些价值观和presses。他认为,这将改变战绩,当然这将创建一个新的记录。

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.

什么是pferred方式prevent这种重复的条目$ P $?我在寻找一个通用的解决方案,也许是基于Cookie或JavaScript的。

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:

在控制器的新的动作时,产生与当前时间的时间戳,并在表格为隐藏字段呈现。当用户提交表单,这个时间戳回来到控制器的创造的行动。创建记录后,该时间戳存储在会话cookie。如果用户通过浏览器的后退按钮返回到新的形式,他得到一个陈旧的形式,这意味着它的时间戳比存储在cookie的老。这是一条错误消息创建记录和结果前检查。

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.

下面是控制器code:

Here is the controller code:

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

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'
  else
    @post.save!
    @stale_form_check_timestamp = Time.now.to_i
    session[:last_created_at] = @stale_form_check_timestamp
  end
end

和这里的形式为code:

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
  = .......

这篇关于扶手:prevent重复插入由于pressing后退按钮,并再次保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆