【发布时间】:2020-10-19 22:05:06
【问题描述】:
我的 rails 应用程序有一个奇怪的问题。我的应用程序在一秒钟内接受重复的 POST 请求
这个包含相同数据的重复请求奇怪地能够绕过我的模型的唯一性验证。这导致创建具有完全相同内容的两行数据。
真正让我感到困惑的是,从昨天开始,它每天只发生一次,我不确定是什么原因造成的。 (系统已经上线,我的客户正在使用,这个方法调用一天使用200-300次,我根本无法重现)
这是我的代码片段和完整代码链接的情况,按时间顺序排列
-
一个用户想要创建一个新的事务,会在控制器上调用这个方法
def new @penjualan = Penjualan.new @penjualan.kode_transaksi = "J"+ DateTime.now.strftime("%d%m%Y%H%M%S")+@active_user.id.to_s @customers = Customer.all(:limit => cookies[:limit], :order=>:kode_kustomer ) @barangs = Barang.all(:limit => cookies[:limit] ) respond_to do |format| format.html # new.html.erb format.json { render json: @penjualan } end endhttp://pastebin.com/Lmp7hncn 第 648 行的完整控制器
-
在“新”视图中,我使用 :disable_with 禁用了按钮,这样用户就不能点击两次提交按钮,从而防止用户发起双重 POST 请求
.row .span4 = f.submit 'Proses', :class=>"btn btn-large btn-primary", :disable_with => "Processing..."http://pastebin.com/7b9W68RY 第 97 行的完整视图
提交的请求将调用控制器上的“create”方法,与 #1 相同的控制器,此方法在 1 秒的差异上被调用两次。更奇怪的是,这个请求绕过了我在模型上定义的唯一性验证,它应该使第二个请求失败,因为它与第一个请求具有相同的 kode_transaksi
-
我的模型 (Penjualan) 属性 (kode_transaksi) 有唯一性约束
class Penjualan < ActiveRecord::Base attr_accessible :customer_id, :jatuh_tempo, :kode_transaksi, :no_sj, :tanggal_bayar, :tanggal_transaksi, :total,:total_diskon, :ongkos, :user_id, :status_pembayaran, :is_returned, :kartu_kredit, :kartu_debit has_many :detil_penjualans attr_accessible :cash_total, :kembali belongs_to :user belongs_to :customer validates :kode_transaksi, :uniqueness =>{:message=>"Transaksi Sudah Terjadi"} scoped_search :on => [:kode_transaksi, :tanggal_transaksi, :status_pembayaran, :tanggal_bayar, :jatuh_tempo, :total ] scoped_search :in => :customer, :on => [:nama_kustomer, :kode_kustomer] scoped_search :in => :user, :on => [:username] end -
我的生产日志和案例的sn-p
Started POST "/penjualans" for 192.168.1.104 at 2012-11-24 12:15:40 +0900 Processing by PenjualansController#create as HTML Parameters: {.... too long, see below ....} Started POST "/penjualans" for 192.168.1.104 at 2012-11-24 12:15:41 +0900 Processing by PenjualansController#create as HTML Parameters: {..... too long, see below ....} Redirected to url/penjualans/17403 Completed 302 Found in 378ms (ActiveRecord: 246.0ms) Redirected to url/penjualans/17404 Completed 302 Found in 367ms (ActiveRecord: 233.8ms)
日志片段http://pastebin.com/3tpua9gi
- 这种情况在我的数据库中创建了一个重复条目,导致问题
我真的对这种行为感到困惑,我束手无策。任何帮助将不胜感激。
【问题讨论】:
-
在旧版本的 :disable_with 中,如果您使用 :disable_with,Rails 生成的 html 中的“onclick”中有一个“this.form.submit”。不知道它是否仍然如此,或者它是否可以解释你的问题。如果用户使用
提交而不是单击按钮,我认为表单无论如何都会提交(虽然它没有被禁用)。如果他们使用 或单击提交按钮会有区别吗?
标签: ruby-on-rails ruby post