我在用 grape 写 api,用了 activerecord,没用 rails
访问 http://localhost:9292/api/v1/users/1 抛异常: ActiveRecord::ConnectionNotEstablished at /api/v1/users/1 No connection pool for User
rake db:create
可以在 mysql 中创建数据库
rake db:migrate
可以在 mysql 中创建表
说明 rake 执行时能连接 mysql 数据库的,高手指教下查询时为何异常?
config/database.yml 代码:
development:
adapter: mysql2
database: grape
encoding: utf8
host: localhost
port: 3306
username: steve
password: steve
pool: 5
timeout: 5000
config.ru 代码
require File.expand_path('../app/api/rest', __FILE__)
require 'active_record'
use ActiveRecord::ConnectionAdapters::ConnectionManagement
run Rest::API
app/api/rest.rb 代码
require 'grape'
require_relative '../models/user'
module Rest
class API < Grape::API
version 'v1', using: :path
format :json
prefix :api
resource :users do
desc '获取一个用户'
params do
requires :id, type: Integer, desc: '用户id'
end
route_param :id do
get do
User.find(params[:id])
end
end
end
end
end
app/models/user.rb 代码
require 'active_record'
class User < ActiveRecord::Base
attr_accessor :name
end
Gemfile
source 'https://ruby.taobao.org'
gem 'grape'
gem 'activerecord'
gem 'active_record_migrations'
gem 'mysql2'
应用启动命令:
rackup config.ru