从DataMapper 文档中,我认为至少需要调用四个函数来设置数据库:
DataMapper.setup(:default, 'sqlite:///path/to/project.db')
DataMapper.finalize
DataMapper.auto_migrate!
DataMapper.auto_upgrade!
在许多 DataMapper+Sinatra 教程中,我了解到这一点auto_migrate!
,并且auto_upgrade!
不应该在每次将应用程序加载到生产服务器上时都调用它。但与此同时,许多示例在 sinatra 应用程序的主 ruby 文件中调用这些函数,例如app.rb
,无需额外检查。有些例子根本没有调用finalize
。到目前为止,我很困惑,我不确定在生产服务器上该怎么做。
拿下面这个简单app.rb
的例子来说,我有一些问题:
- 应该在何时何
finalize
地调用? - 第一次部署应用程序时,生产服务器上没有
db
文件,我如何自动创建它?还是我必须project.db
手动创建文件? - 由于
auto_upgrade!
包装在:development
块中,因此不会在生产服务器上调用它。当我添加或删除其中的列时,我应该如何升级数据库?
require 'sinatra'
require 'data_mapper'
configure do
DataMapper.setup :default, "sqlite3://#{Dir.pwd}/project.db"
end
class Book
include DataMapper::Resource
property :id, Serial
property :title, Text
belongs_to :author
end
class Author
include DataMapper::Resource
property :id, Serial
property :name, Text
has n, :books
end
configure :development do
DataMapper.auto_upgrade!
end
get '/:id' do
@author = Author.get params[:id]
erb :list_author_and_his_books # The template has nothing to do with this question, ignore it
end
get '/new' do
# Some code for user to input book or author details
end
get '/create' do
# Some code to create book or author in db
end
感谢您阅读这篇长文:D