Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table if not present in existing database using Rails 3

I have a doubt.Suppose i have already created model(i.e-User) in Rails 3 application.Now i will connect my app to other database(lets say SQL Server) instead of my DB(where i have created this model before).That Database where i am going to connect has no "User" table and my app has already User.rb file.Here i need when i will connect to my app to that DB,it will automatically execute the query and create table in that DB.Please check my User migration file given below.

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

User.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

When user will connect to any other DB,The table should auto created.Please help me.

like image 940
rajat_474 Avatar asked May 02 '15 12:05

rajat_474


1 Answers

Change your migration file to check before creating/destroying users

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
like image 91
Shahzad Tariq Avatar answered Oct 22 '22 13:10

Shahzad Tariq