make rake db:create setup another database besides development, test or production

458 views Asked by At

I'm using rails 4.2 and trying to configure (in a already established application) the Audited Gem following this second database approach.

My config/database.yml file was as follows:

default: &default
  adapter: mysql2
  pool: 5
  timeout: 5000

development:
  <<: *default
  host:  <%= ENV["MYSQL_HOST"] %>
  username: <%= ENV["MYSQL_USER"] %>
  password: <%= ENV["MYSQL_PASSWORD"] %>
  database: <%= ENV["MYSQL_DATABASE"] %>

test:
  <<: *default
  host:  <%= ENV["MYSQL_HOST"] %>
  username: <%= ENV["MYSQL_USER"] %>
  password: <%= ENV["MYSQL_PASSWORD"] %>
  database: <%= ENV['TEST_ENV_DB'] %>

And I intend to make it work for another db, besides development, test or production. However the task rake db:create only creates my development and test database. Is this possible to accomplish in my rails version?

audition:
  <<: *default
  host:  <%= ENV["MYSQL_HOST"] %>
  username: <%= ENV["MYSQL_USER"] %>
  password: <%= ENV["MYSQL_PASSWORD"] %>
  database: <%= ENV["AUDITION_DATABASE"] %>

Note the new name for audition database

3

There are 3 answers

4
Hany Moh. On

I think you want to create a new environment call audition, Right?!.

  • Clone an existing environment file for instance, config/environments/test.rb and rename it config/environments/audition.rb
  • Add a new configuration block in config/database.yml for your environment.
  • Update any other configuration file you might have under the config folder with your new environment, some gems need to config it.

  • Now you can start the server

rails server -e audition

1
PGill On

if you want to read/write to a seconds database in rails < 6

create a module

module AuditionConn
  def self.included(base)
    base.class_eval do
     if Rails.env == 'development'
       establish_connection "audition-development" # database.yml
      else
       establish_connection "audition-production" # database.yml
      end
    end
  end
end

then include it in any model you want to read/write from/to auditions database

class AuditionDBModel < ActiveRecord::Base
  include AuditionConn
end

migration for second database

def up
  AuditionDBModel.connection.create_table ... do |t|
    ...

  AuditionDBModel.connection.change_column ...
end
0
shashwat srivastava On

I think this may help you:
create another model for audit:

class AuditModel < ActiveRecord::Base
  connects_to database: { writing: :audit_db, reading: :audit_db}
end

or

ActiveRecord::Base.establish_connection(
  adapter:  "mysql2",
  host:     "localhost",
  username: "myuser",
  password: "mypass",
  database: "somedatabase"
)

for details: https://guides.rubyonrails.org/active_record_multiple_databases.html https://edgeapi.rubyonrails.org/classes/ActiveRecord/ConnectionHandling.html