13

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的例子来说,我有一些问题:

  1. 应该在何时何finalize地调用?
  2. 第一次部署应用程序时,生产服务器上没有db文件,我如何自动创建它?还是我必须project.db手动创建文件?
  3. 由于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

4

1 回答 1

7

Where and when should finalize be called?

From http://rdoc.info/github/datamapper/dm-core/DataMapper#finalize-class_method

This method should be called after loading all models and plugins.

When deploying the app first time there is no db file on the production server, how do I have it automatically created? Or do I have to create the project.db file manually?

It depends on your hosting arrangement, but the main thing to do is put the running of migrations in a Rake task and run them when the app is deployed. If you're using Sqlite, this would create the database (although on some hosts you are not allowed to update the file system). I don't think it's a good idea to use Sqlite for a production database, but that's your decision.

Since the auto_upgrade! is wrapped in :development block, it won't be called on production server. How am I supposed to upgrade database when I add or remove columns in it?

Use a Rake task. After each deployment you'd run the "db:migrate:up" (or whatever you'd called it) task and it would run the latest migrations. You might get a few ideas from Padrino's Rake tasks for DataMapper

于 2013-05-02T13:25:39.453 回答