Ruby on rails - how to retrieve connection strings
Are there any ways to retrieve the database connection string where my ruby is connected? what i would like to get is the:
1) Database name where the ruby is connected 2) The username of the SQL Server 3) Password of the SQL Server 4) Server nam开发者_JAVA技巧e
I want to store it in session variables.
(I'am using MS SQL Server.)
Please help! thanks!
I would go with ActiveRecord::Base.connection_config
which returns hash with options for ActiveRecord 3.
You can access all of the properties described in your database.yaml like this:
ActiveRecord::Base.configurations["development"] =>
{"encoding"=>"utf8", "username"=>"foo", "adapter"=>"mysql", "database"=>"bar_development", "host"=>"localhost", "password"=> "baz"}
These values are all stored in the file config/database.yml
, but AFAIK you can't access these values as variables from within your controller.
Database: ActiveRecord::Base.connection.current_database
You could also do some fancy Regexs with the following:
ActiveRecord::Base.connection.inspect
But yeah, this is a terrible idea.
There's a connection_db_config
which returns ActiveRecord::DatabaseConfigurations::UrlConfig
object, which looks like this
> ActiveRecord::Base.connection_db_config
=> #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x000055794c915ad0
@configuration_hash=
{:adapter=>"postgresql",
:encoding=>"unicode",
:pool=>5,
:username=>"postgres",
:password=>nil,
:host=>"localhost",
:port=>5432,
:database=>"oyster_development"},
@env_name="development",
@name="primary",
@url="postgresql://postgres@localhost:5432">
Calling url
will give you connection URL:
> ActiveRecord::Base.connection_db_config.url
=> "postgresql://postgres@localhost:5432"
You can append it with database name, to get (what I believe) is a full connection string
> "#{ActiveRecord::Base.connection_db_config.url}/#{ActiveRecord::Base.connection_db_config.database}"
=> "postgresql://postgres@localhost:5432/your_project_development"
The most upvoted answer no longer works on more recent versions of ruby. The below does the same thing.
Rails.configuration.database_configuration[Rails.env]
精彩评论