raj*_*474 5 ruby ruby-on-rails-3.2
我有一个疑问。假设我已经在 Rails 3 应用程序中创建了模型(即用户)。现在我将我的应用程序连接到其他数据库(比如 SQL Server)而不是我的数据库(我之前在那里创建了这个模型)。我要连接的那个数据库没有“用户”表,我的应用程序已经有 User.rb 文件。在这里我需要什么时候我将我的应用程序连接到那个数据库,它会自动执行查询并在那个数据库中创建表.请检查下面给出的我的用户迁移文件。
20150419131135_create_users.rb:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :contact_name
t.string :login_id
t.string :password_hash
t.string :password_salt
t.string :phone
t.string :address
t.timestamps
end
end
end
Run Code Online (Sandbox Code Playgroud)
用户.rb:
class User < ActiveRecord::Base
attr_accessible :address, :contact_name, :login_id, :password_hash, :password_salt, :phone,:password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates :contact_name, :presence => true, :length => { :minimum => 5 }
validates :login_id, :presence => true
validates_uniqueness_of :login_id
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
def self.authenticate(username, password)
user = find_by_login_id(username)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
end
Run Code Online (Sandbox Code Playgroud)
当用户连接到任何其他数据库时,表应该自动创建。请帮助我。
更改迁移文件以在创建/销毁用户之前进行检查
class CreateUsers < ActiveRecord::Migration
def self.up
if !table_exists? :users
create_table :users do |t|
t.string :contact_name
t.string :login_id
t.string :password_hash
t.string :password_salt
t.string :phone
t.string :address
t.timestamps
end
end
end
def self.down
drop_table :users if !table_exists?(:users)
end
end
Run Code Online (Sandbox Code Playgroud)