加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 我们如何规避这些远程形式的缺点?

发布时间:2020-12-17 04:00:09 所属栏目:百科 来源:网络整理
导读:为了在我们的网站上翻译所有内容(包括验证的错误消息),我们几乎将所有表单切换为远程表单.虽然这有助于翻译错误消息,但我们遇到了其他问题,例如: 如果用户多次单击提交按钮,则会多次调用该操作.如果我们有一个用于在数据库中创建新记录的远程表单,并假设用
为了在我们的网站上翻译所有内容(包括验证的错误消息),我们几乎将所有表单切换为远程表单.虽然这有助于翻译错误消息,但我们遇到了其他问题,例如:

>如果用户多次单击提交按钮,则会多次调用该操作.如果我们有一个用于在数据库中创建新记录的远程表单,并假设用户的数据有效,则每次单击将添加一个新对象(具有完全相同的内容).有没有办法确保这些事情不会发生?

有什么地方我可以阅读有关远程表单最佳实践的内容吗?我怎么能处理多次点击问题?将所有表单切换到远程表单是一个非常大的错误吗?

解决方法

最简单的解决方案是为每个表单生成一个令牌.然后,您的创建操作可以确保它尚未使用,并确定是否应创建记录.

以下是我将如何编写此功能.请注意,我实际上没有测试过这个,但这个概念应该可行.

1.
在新操作内部创建一个哈希来标识表单请求.

def new
  @product = Product.new
  @form_token = session["form_token"] = SecureRandom.hex(15)
end

2.
向存储表单标记的表单添加隐藏字段.这将在创建操作中捕获,以确保之前未提交表单.

<%= hidden_field_tag :form_token,@form_token %>

3.
在create操作中,您可以确保表单标记在session和params变量之间匹配.这将使您有机会查看这是第一次提交还是第二次提交.

def create
  # delete the form token if it matches
  if session[:form_token] == params[:form_token]
    session[:form_token] = nil
  else
    # if it doesn't match then check if a record was created recently
    product = Product.where('created_at > ?',3.minutes.ago).where(title: params[:product][:title]).last

    # if the product exists then show it
    # or just return because it is a remote form
    redirect_to product and return if product.present?
  end

  # normal create action here ...
end

更新:我上面描述的有一个名字,它被称为同步器(或Déjàvu)令牌.如in this article所述,是防止双重提交的正确方法.

This strategy addresses the problem of duplicate form submissions. A synchronizer token is set in a user’s session and included with each form returned to the client. When that form is submitted,the synchronizer token in the form is compared to the synchronizer token in the session. The tokens should match the first time the form is submitted. If the tokens do not match,then the form submission may be disallowed and an error returned to the user. Token mismatch may occur when the user submits a form,then clicks the Back button in the browser and attempts to resubmit the same form.

On the other hand,if the two token values match,then we are confident that the flow of control is exactly as expected. At this point,the token value in the session is modified to a new value and the form submission is accepted.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读