我已经在Heroku上部署了我的Ruby应用程序,但是在注册或登录时我遇到了一个内部服务器错误。我的应用程序是在Sinatra和Rake上构建的。
当执行heroku logs -tail
时,我收到以下错误消息:
PG::ConnectionBad - connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
Is the server running locally and accepting connections on that socket?
我安装了heroku Postgres插件。我使用以下命令迁移了我的数据库:heroku pg:push makersbnb DATABASE --app makersbnb-challenge
个
下面是一个带有PG连接的lib文件:
require 'bcrypt'
class User
attr_reader :user_id, :username
def initialize(user_id:, username:)
@user_id = user_id
@username = username
end
def self.register(username:, password: )
if ENV['ENVIRONMENT'] == 'test'
connection = PG.connect(dbname: "makersbnb_test")
else
connection = PG.connect(dbname: 'makersbnb')
end
encrypted_password = BCrypt::Password.create(password)
result = connection.exec_params("INSERT INTO users (username, password)
VALUES ($1, $2)
RETURNING user_id, username, password;",[username, encrypted_password])
User.new(user_id: result[0]['user_id'], username: result[0]['username'])
end
def self.authenticate(username:, password:)
if ENV['ENVIRONMENT'] == 'test'
connection = PG.connect(dbname: "makersbnb_test")
else
connection = PG.connect(dbname: 'makersbnb')
end
result = connection.query(
"SELECT * FROM users WHERE username = $1",
[username]
)
return unless result.any?
return unless BCrypt::Password.new(result[0]['password']) == password
User.new(user_id: result[0]['user_id'], username: result[0]['username'])
end
end
下面是我的宝石文件:
source "https://rubygems.org"
ruby '3.1.0'
gem "sinatra"
gem "sinatra-contrib"
gem "rake"
gem 'pg'
gem 'webrick'
gem 'bcrypt'
gem 'rack-flash3'
gem "sinatra-activerecord" # for Active Record models
gem 'capybara', group: :test
gem 'rspec', group: :test
我还根据我阅读的其他说明创建了一个数据库.yml文件,但我不确定它是否适用于本例:
# database.yml file
default: &default
adapter: postgresql
encoding: unicode
pool: 5
test:
<<: *default
database: makersbnb_test
production:
<<: *default
database: makersbnb
1条答案
按热度按时间vshtjzan1#
我将试着解释这个问题,同时也指出当前方法的一些其他缺陷。要连接到远程数据库,您应该在
您不仅应指定dbname选项,还应指定:
请记住,不要在代码中设置这些值您可以使用env变量。
在这里您可以找到一些如何使用ActiveRecord而不使用Rails框架的信息:https://www.devdungeon.com/content/ruby-activerecord-without-rails-tutorial以及如何在sinatra中具体使用它的更多信息:https://github.com/sinatra-activerecord/sinatra-activerecord