shanmuk1729
shanmuk1729

Reputation: 49

Strategies for overriding database.yml

There is another question on stackoverflow with this title. This is the link to that. My question is a little different but almost on the same line

I work with a database that has multiple users each having a unique set of privileges to the database. Hence I can't hard code the database login details in the database.yml. Instead I want to create a html form which collects the login credentials. I understand that database.yml can be written in the erb way from this link. But by the time, my index.html(the page in which I have written my form) is shown, the attempt to establish connection is done and it is throwing an error saying nil is provided for username and password. Please let me know how to approach this problem.

I am new to rails, so please ask me if I didn't provide enough information. Thanks in advance

Upvotes: 1

Views: 1644

Answers (1)

jamuraa
jamuraa

Reputation: 3419

Use ActiveRecord::ConnectionHandling.establish_connection function call to connect to your database. You should be able to establish a connection with a different user even on every page if you would like, or look up the database credentials in a User model.

If you are doing this, you might consider subclassing ActiveRecord::Base and overriding the connection call, which would then be used by every model to connect to the database.

If you want to completely avoid a connection to the database before you explicitly set up the credentials through your application, then you probably want to initialize Rails without loading all of the ActiveRecord specific stuff. In that case, you will need to remove ActiveRecord from the initialization of Rails by putting this line in your config/environment.rb, within the Rails::Initializer.run do |config| block:

config.frameworks -= [ :active_record ]

Then you will need to load all of the ActiveRecord specific things once you have the credentials.

Alternatively, you can override Rails::Initialize::initialize_database which is where the actual database connection is being used by putting this in your environment.rb before the Rails::Initializer.run call:

module Rails
  class Initializer
    def initialize_database
      nil
    end
  end
end

Prior to rails 4.x you would use ActiveRecord::Base.establish_connection, which is now deprecated.

Upvotes: 3

Related Questions