Ruby 使用Rails 3创建现有数据库中不存在的表
我有一个疑问。假设我已经在Rails 3应用程序中创建了模型(即e-User)。现在我将把我的应用程序连接到其他数据库(比如SQL Server),而不是我的数据库(我以前创建过这个模型)。我要连接的数据库没有“用户”表和我的应用程序已经有User.rb文件。在这里我需要当我将我的应用程序连接到该数据库时,它将自动执行查询并在该数据库中创建表。请检查下面给出的我的用户迁移文件 20150419131135_create_users.rb:Ruby 使用Rails 3创建现有数据库中不存在的表,ruby,ruby-on-rails-3.2,Ruby,Ruby On Rails 3.2,我有一个疑问。假设我已经在Rails 3应用程序中创建了模型(即e-User)。现在我将把我的应用程序连接到其他数据库(比如SQL Server),而不是我的数据库(我以前创建过这个模型)。我要连接的数据库没有“用户”表和我的应用程序已经有User.rb文件。在这里我需要当我将我的应用程序连接到该数据库时,它将自动执行查询并在该数据库中创建表。请检查下面给出的我的用户迁移文件 20150419131135_create_users.rb: class CreateUserstrue,:lengt
class CreateUsers
User.rb:
class用户:create
验证:contact_name,:presence=>true,:length=>{:minimum=>5}
验证:login\u id,:presence=>true
验证登录id的唯一性
def加密密码
如果密码存在?
self.password\u salt=BCrypt::Engine.generate\u salt
self.password\u hash=BCrypt::Engine.hash\u secret(密码、密码)
结束
结束
def自我验证(用户名、密码)
user=find\u by\u login\u id(用户名)
如果user&&user.password\u hash==BCrypt::Engine.hash\u secret(密码,user.password\u salt)
用户
其他的
无
结束
结束
结束
当用户将连接到任何其他数据库时,表应自动创建。请帮助我。在创建/销毁用户之前,将迁移文件更改为检查
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
class CreateUsers
你正在连接什么数据库?@Cyzanfar:我想连接SQL Server谢谢<代码>除非表_存在?将是更为ruby的编写方式:)。此外,我认为在放下桌子之前,没有必要检查是否缺少桌子。
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
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