1

I have a Rails v 2.0.2 application. I'd like to initialize a constant in initializers/constants.rb and set its value from DB.

smth like this:

SESSION_DURATION = SystemDB::Configuration.get('session_duration', 0).to_i.minutes

So i've got a Configuration table in PostgreSQL with row where name = 'session_duration'. This code works fine on my local Windows PC but it fails on production server with Linux with error: `retrieve_connection': ActiveRecord::ConnectionNotEstablished (ActiveRecord::ConnectionNotEstablished)

It seems to me that at the time rails initializes the constants.rb file ActiveRecord has not been initialized yet. What can i do with it?

By The Way. I use this constant in module - so it must me initialized as soon as possible. (if i understand well)

1 Answer 1

1

This probably isn't the best way to do it.. If you're wanting to set a constant from a field in a database then I'm assuming it's actually a variable and not a constant. If the value changes, your application isn't actually going to pick up the change until you restart your web server. You're probably better off making a database call instead of using a reference to SESSION_DURATION in your application.. Database calls are cheap. You may want to rethink your approach.

That said, you know your application better than I do and there may be a reason you need to do this.. If that's the case, this is a bit messy but you could always just require activerecord in your constants file and manually connect to your database first..

require "rubygems"
require "activerecord"

ActiveRecord::Base.establish_connection (
  :adapter => "mysql",
  :host => "localhost",
  :username => "user",
  :password => "password",
  :database => "some_database")

All the best ;)

Sign up to request clarification or add additional context in comments.

2 Comments

I need to use constants and this way will duplicate DB config which is not good, but any way, thanks.
Maybe i can put CONSTANTS in other file? but i need that constants to be accessed in modules (/lib/ directory)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.