我正在尝试在非 Rails 项目中使用 ActiveRecord 和 rails 迁移。我安装了standalone_migrations gem,它似乎可以工作。为了测试,我创建了两个迁移
rake db:new_migration name=users
rake db:new_migration name=logins
这是我的迁移文件:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.string :full_name, :null => false
# Database authenticable
t.string :username, :null => false, :default => '', :unique => true
t.string :encrypted_password, :null => false, :default => ''
end
end
def self.down
drop_table :users
end
end
class CreateLogins < ActiveRecord::Migration
def self.up
create_table :logins do |t|
t.integer :user_id, :null => false
t.datetime :logged_in_at, :null => false
t.datetime :logged_out_at, :null => false
end
end
def self.down
drop_table :logins
end
end
然后我跑了rake db:migrate
,它似乎工作:
== CreateUsers: migrating ====================================================
-- create_table(:users)
-> 0.0020s
== CreateUsers: migrated (0.0020s) ===========================================
== CreateLogins: migrating ===================================================
-- create_table(:logins)
-> 0.0020s
== CreateLogins: migrated (0.0020s) ==========================================
我有一个db/migrate
文件夹和一个db/config.yml
配置,就像standalone_migrations gem 手册中一样。但是,当我创建用户模型时:
require '../../db/dbconnect'
p ActiveRecord::Base.connection.tables
class User < ActiveRecord::Base
end
User.new
首先,我得到一个空列表,然后是一个异常
Could not find table 'users' (ActiveRecord::StatementInvalid)
我该怎么做才能让它发挥作用?
编辑1:
我的db/config.yml
:
development:
adapter: sqlite3
database: development.db
encoding: utf8
production:
adapter: sqlite3
database: aquareader.db
encoding: utf8
test: &test
adapter: sqlite3
database: test.db
encoding: utf8
我的db/dbconnect.rb
:
require 'rubygems'
require 'active_record'
require 'yaml'
# read the connection information from the database config file
dbconfig = YAML::load(File.open(File.expand_path(File.dirname(__FILE__) + '/config.yml')))
# connect to the database
ActiveRecord::Base.establish_connection(dbconfig['development'])
编辑2:
我发现我的developement.db
表正在使用正确的表和所有内容在我的根文件夹中创建我的迁移。但是,当我运行lib/myproject/users.rb
它时,它会在项目目录中创建一个development.db
并且不使用dbconnect.rb
文件中指定的那个。任何想法为什么?