Postgres:准备好的声明已经存在

时间:2014-10-21 16:52:10

标签: ruby-on-rails ruby postgresql devise

我在我的Rails API应用程序中使用Devise进行身份验证。有时我在日志中看到以下错误:

  

ActiveRecord :: StatementInvalid:PGError:错误:准备好的语句   “a3926”已经存在:UPDATE“users”SET“current_sign_in_at”= $ 1,   “last_sign_in_at”= $ 2,“sign_in_count”= $ 3,“updated_at”= $ 4 WHERE   “users”。“id”= 12345

错误来自Devise:

  def update_tracked_fields!(request)
    old_current, new_current = self.current_sign_in_at, Time.now.utc
    self.last_sign_in_at     = old_current || new_current
    self.current_sign_in_at  = new_current

    old_current, new_current = self.current_sign_in_ip, request.remote_ip
    self.last_sign_in_ip     = old_current || new_current
    self.current_sign_in_ip  = new_current

    self.sign_in_count ||= 0
    self.sign_in_count += 1

    # error happens below
    save(validate: false) or raise "Devise trackable could not save #{inspect}." \
      "Please make sure a model using trackable can be saved at sign in."
  end

据我所知,当数据库连接的使用方式出现问题时,通常会发生此错误。有什么我应该找的吗?

1 个答案:

答案 0 :(得分:1)

如果您使用的服务器会分叉您的进程(例如独角兽),则需要为每个分叉进程创建一个连接。

如果是独角兽,请添加:

#config/unicorn.rb
before_fork do |server, worker|

  Signal.trap 'TERM' do
   puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
   Process.kill 'QUIT', Process.pid
 end

  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.connection.disconnect!
end

after_fork do |server, worker|

  Signal.trap 'TERM' do
    puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to sent QUIT'
  end

 defined?(ActiveRecord::Base) and
   ActiveRecord::Base.establish_connection(
     Rails.application.config.database_configuration[Rails.env]
   )

end