我在我的rails api应用程序中使用devise进行身份验证。有时我在日志中看到以下错误:
activerecord::statementInvalid:pgerror:error:prepared语句
“a3926”已经存在:更新“users”设置“current_sign_in_at”=1美元,
“最后登录时间”=2美元,“登录次数”=3美元,“更新时间”=4美元,其中
“用户”。“id”=12345
错误是由设计出来的:

  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

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

最佳答案

如果使用分叉进程的服务器(如unicorn),则需要为每个分叉进程创建连接。
如果是独角兽,请添加以下内容:

#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

10-06 04:57