在使用带有sinatra的ActiveRecord创建应用程序时,我遇到了这样的错误。
> ActiveRecord :: ConnectionTimeoutError at /无法获取数据库 连接在5.000秒内(等待5.005秒)
我要做的是“从Twitter API获取个人资料图片,将其保存在数据库中,并将其嵌入index.erb”。我在这里停了下来。
代码如下。
main.rb的
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
index.erb
require "sinatra"
require "sinatra/reloader"
require "twitter"
require "active_record"
ActiveRecord::Base.establish_connection(
adapter: "sqlite3",
database: "./image.db"
)
class Src < ActiveRecord::Base
end
def get_profile_image
@srcs = Src.order("id desc").all
end
def add_profile_image(twitter_id)
client = Twitter::REST::Client.new(
consumer_key: "[CONSUMER_KEY]",
consumer_secret: "[CONSUMER_SECRET]",
access_token: "[ACCESS_TOMEN]",
access_token_secret: "[ACCESS_TOKEN_SECRET]"
)
user = client.user(twitter_id)
url = user.profile_image_url
src = Src.new(account: twitter_id, url: url)
src.save
end
def delete_img(twitter_id)
Src.find_by(account: twitter_id).delete
end
get "/" do
get_profile_image
erb :index
end
post "/" do
add_profile_image(params[:id])
get_profile_image
erb :index
end
get "/delete" do
delete_img(params[:id])
get_profile_image
erb :index
end
数据库表名称为“srcs”,列为
这种错误对我来说是第一次,但问题出在哪里?
答案 0 :(得分:0)
在单独的脚本中将与数据库的连接与代码分离,以测试和发布产生的错误,以便我们可以重现问题,例如
require "active_record"
ActiveRecord::Base.establish_connection(
adapter: "sqlite3",
database: "./image.db"
)
if !ActiveRecord::Base.connection.table_exists?('SRCS')
ActiveRecord::Schema.define do
create_table 'SRCS' do |table|
table.column :account, :string
table.column :url, :string
end
end
end
class Src < ActiveRecord::Base
self.table_name = 'SRCS'
end
p Src.first