Rails database name dynamically by user choice in Mongodb - ruby-on-rails

While installing my app , I want to ask question like
Name of database?
and user will input name they want for database.
Database name is inside config/mongoid.yml
development:
sessions:
default:
database: project_development
hosts:
- localhost:27017
options:
I want to make the database like project_development dynamically by user input while performing bundle install or before bundle install for app.Is there any steps to make this happen?

If config/mongoid.yml is passed through ERB like config/database.yml is, then you can do the following trick:
development:
sessions:
default:
database: <%= ENV['MONGO_DB_NAME'] || 'default_db_name' %>
hosts:
- localhost:27017
options:
Then start rails with MONGO_DB_NAME=some_name rails s. If you omit MONGO_DB_NAME from startup, it will fallback to default_db_name.

Related

What is the best solution to store password in rails yml file?

I hard code the username and password in the database.yml file in my rails project. But I am afraid that if I upload it into github,my password may be leaked.
So what is the general solution to safely store the password in rails file?
This piece of code is how I stored the password.
Thanks.
development:
<<: *default
adapter: postgresql
encoding: unicode
database: myapp_development
pool: 5
username: myapp
password: 123456789
If you are using Rails > 5.2 then you can use rails Credentials. If it doesn't exist, a key will be created when you run rails credentials:edit.
You can edit it like below -
EDITOR=vim rails credentials:edit
and add like below -
postgres:
username:
development: ABC
staging: XYZ
password:
development: Yzx234354
staging: "fooBar%#3"
The in your database.yml you can use it like -
development:
<<: *default
adapter: postgresql
encoding: unicode
database: myapp_development
pool: 5
username: Rails.application.credentials.dig(:postgres, :username, :development)
password: Rails.application.credentials.dig(:postgres, :password, :development)
Just put the master.key in .gitignore and you will be safe from all confusions.
Another option next to using the rails credentials (as answered by Rafayet Monon) would be using an .env file that you put into the root of your rails project (and don't check into git). Inside your app, you just use ENV['MY_VAR'] (or ENV.fetch('MY_VAR', 'default value if not defined')).
This can be easily done through the dotenv-rails gem that is based on https://github.com/bkeepers/dotenv.
I'm using this approach because I also have to handle a variety of other projects (e.g. php based ones) and every project uses the same .env approach to keep it consistent for the project teams. As an additional help, a _.env.example is committed that contains all the possibilities with a short documentation, so everyone that has to set up the project knows what has to be configured in order to get it up and running.
Also, a nice feature of the ruby dotenv implementation is to check the presence of required variables, which can be put into an initializer. The dotenv README has a section about this.
For anyone coming here looking for an answer and using rails > 6
start by:
rails credentials:edit --environment production // or development or test
add:
mysql:
username: root
password: password
then in database.yml:
username: <%= Rails.application.credentials.dig(:mysql, :username) %>
password: <%= Rails.application.credentials.dig(:mysql, :password) %>
restart rails and you're good to go
Note: that must be generated for all the environments
I don't think you need a database username and password. You can just remove those lines. In development environment (localhost) the database is just on your computer so no one else can access it. In production, if you use heroku, they will take care of adding a username and password.

Rails postgres default database user when using --database=postgresql

I feel like I should know this, but I don't! 😞
When creating a new rails app with --database=postgresql the database.yml looks like:
...
default: &default
adapter: postgresql
encoding: unicode
# For details on connection pooling, see Rails configuration guide
# http://guides.rubyonrails.org/configuring.html#database-pooling
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: big_bustas_development
...
Now I can do all manner of rails db:create ...migrate...ect without explitly configuring a database user and password. What postgres credentials is rails using the accomplish this?
PostgreSQL by default use your OS username. The default authentication mode for PostgreSQL is set to ident. Read this article and/or docs for more information.

Rails: fe_sendauth: no password supplied (PG::ConnectionBad) from Ruby, but ok in Rails

I'm having problems assessing a postgres database from straight ruby.
I've created a Postgres database using Rails
>rails new www --database=postgresql
using Rails 4.2.5 and Postgres is 9.4
It produces the following config/database.yml file.
default: &default
adapter: postgresql
encoding: unicode
pool: 5
development:
<<: *default
database: www_development
test:
<<: *default
database: www_test
production:
<<: *default
database: www_production
username: www
password: <%= ENV['WWW_DATABASE_PASSWORD'] %>
I can run rails server, db:drop, db:create and db:migrate fine.
I can also access the database fine with psql
>psql www_development
But when I run the following app.rb from a non Rails project directory, I get a fe_sendauth: no password supplied (PG::ConnectionBad) error message.
It's clearly not a Rails issue. I've either missed something in my ruby or Postgres need a tweek to handle some difference between Rails and pure Ruby [that I'm not aware off]. I've also included Postgres' pg_hba.conf file.
At wits end trying to figure this one out. Any help would be much appreciated.
app.rb
require 'yaml'
require 'active_record'
require 'pg'
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
database: 'www_development',
)
/etc/postgresql/9.4/main/pg_hba.conf
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer
local all all peer
host all all 127.0.0.1/32 md5
host all all ::1/128 md5
You don't specify neither username, no password in your ActiveRecord::Base.establish_connection(. I assume you want to use some SUPERUSER without password for www_development database - right?
as per documentation peer auth does
Obtain the client's operating system user name from the operating
system and check if it matches the requested database user name.
That is why if you can psql without password, you should be able run app.rb with same OS user and environment without password. If you can't, then app.rb tries to connect with different username or so...
Options:
put username: postgres to ActiveRecord::Base.establish_connection(
change local all all peer to local all all trust
With ENV variable as password it's very likely that the variable itself is not present. Confirm the presence with printenv. You need to relogin/reboot for the variable to be accessible after you've included it in /etc/environment file for example. If this works, it's probably better than changing pg_hba.conf.
development:
<<: *default
database: postgres
username: postgres
password: postgres
# must specify the right DB, superuser and superuser Password as per postgreSQL setup
This worked for me, the only changes I needed to make. (ok fine i re-installed pgsql with 12.1)
I had this same issue when setting up a Rails 6 application.
The issue was that when start the rails server using rails server, and try to view the application from a browser, I get the error below:
ActiveRecord::ConnectionNotEstablished
fe_sendauth: no password supplied
Here's how I solved it:
The issue was caused by me not specifying/supplying the database password to be used by the application, so when the application tries to connect to the database specified in the config/database.yml it runs into that error.
I solved it by specifying the database password for the application in the config/database.yml:
# The password associated with the postgres role (username).
password: my-password
Also, ensure that you've created the database for the application if you've not created it already using:
rails db:create
Afterwhich I restarted the rails server:
rails server
This time when I tried viewing the application from the browser, it worked fine.
That's all.
I hope this helps
I was trying to use peer authentication which shouldn't ask for the password.
For me the issue was that I was specifying localhost in the database.yml so that was forcing the database driver to try to make a different type of connection (e.g., tcp, named pipe, etc)
Removing the "host: 'localhost'" line from my config solved the problem for me per this other answer: ActiveRecord connection to a localhost postgresql database in trust mode
Note that in my case I'm using the 'peer' method and not the 'trust' method but the solution is the same

Rails Engine + Mongoid: No configuration could be found for a session named 'default'

I've created a Rails Mountable App and added 'mongoid' and 'rspec' gem's. If I try to run my specs now I get the following error:
Mongoid::Errors::NoSessionConfig:
Problem:
No configuration could be found for a session named 'default'.
Summary:
When attempting to create the new session, Mongoid could not find a session configuration for the name: 'default'. This is necessary in order to know the host, port, and options needed to connect.
Resolution:
Double check your mongoid.yml to make sure under the sessions key that a configuration exists for 'default'. If you have set the configuration programatically, ensure that 'default' exists in the configuration hash.
When I add the Mongoid.load!(Rails.root.join("config", "mongoid.yml")) line to spec_helper.rb everything works normal.
Why is that and how can I get the functionality like in a normal Rails app where I don't need to call the load function?
mongoid.yml
development:
sessions:
default:
database: dummy_development
hosts:
- localhost:27017
options:
options:
test:
sessions:
default:
database: dummy_test
hosts:
- localhost:27017
options:
consistency: :strong
max_retries: 1
retry_interval: 0
Versions:
gem 'rails', '~> 3.2.12'
gem 'mongoid', '~> 3.1'
gem 'rspec-rails', '~> 2.13'
you probably missed require 'rails/mongoid' in your spec_helper.rb file.
Had someone having the same issue in here https://github.com/mongoid/mongoid/issues/2894#issuecomment-14903927
Try adding that require, that should fix it.
This worked for me on my machine
1: Add this to your config/application.rb
Mongoid.load!("path to your mongoid.yml")
2: And change your mongoid.yml from (Only for mongoid version < 5):
This
development:
clients:
default:
database: database_for_development
hosts:
- localhost:27017
test:
clients:
default:
database: database_for_test
hosts:
- localhost:27017
production:
clients:
default:
database: database_for_production
hosts:
- localhost:27017
To:
development:
sessions:
default:
database: database_for_development
hosts:
- localhost:27017
test:
sessions:
default:
database: database_for_test
hosts:
- localhost:27017
production:
sessions:
default:
database: database_for_production
hosts:
- localhost:27017
This is probably because of two simultaneous conditions: ( there is no production section in mongoid.yml ) AND ( Heroku treats Rails applications as production by default ).
Fixing either one shall suffice.
1. There is no production section in mongoid.yml
Add production section to mongoid.yml, as explained at Heroku , e.g.
production:
sessions:
default:
uri: <%= ENV['MONGOHQ_URL'] %>
options:
skip_version_check: true
safe: true
2. Heroku treats rails applications as production by default
Set Heroku environment to development, or a add a new environment which would be specific to Heroku, as explained at Heroku, e.g.
heroku config:set RACK_ENV=development RAILS_ENV=development --remote development
And restart the server after making changes to mongoid.yml
I've found this working - notice there is no "sessions", only "clients"
production:
clients:
default:
uri: <%= ENV['MONGODB_URI'] %>
options:
skip_version_check: true
safe: true
Try to regenerate a new mongoid.yml:
rails g mongoid:config
And after change mongoid.yml with your values.

rails 3 postgreSQL basic 'database does not exist'

OK, I'm building my first rails 3.0 app and want to test the postgreSQL server as production on my development machine (which is running 10.6). When you create a new app and rake db:migrate it creates sqlite db's for all three environments. Cool. Now I want to learn how to move to production and use postgres. I've used homebrew to install postgres, installed the pg (env ARCHFLAGS="-arch x86_64" gem install pg) and postgres-pr gems.
I've run rake db:migrate in hope that like with sqlite3 it will auto build my production server since I've updated my database.yml (see below).
OK, in my app's folder, I restart the server using 'rails s --environment=production' and it bails saying it cannot find my production database.
So all the google searches for 'rails 3 postgres install' got me this far, but I appear to be missing something because rails is failing to create the new pg database.
postgres is running as determined by ps.
createdb -Omysuperusername -Eutf8 vitae_production
createdb -Omysuperusername -Eutf8 /Users/sam/apps/vitae/db/vitae_production
But this directory does not have this database so I'm missing something. What am I overlooking?
this is my database.yml snippet:
production:
adapter: postgresql
host: localhost
database: db/vitae_production
pool: 5
timeout: 5000
username: mysuperusername
password:
There are a couple things going on here. First of all, you seem to be mixing the SQLite and PostgreSQL format for the database: setting in your database.yml. With SQLite, you specify the relative path to the SQLite database file with something like:
database: db/vitae_production.sqlite
but with PostgreSQL, you specify the database name with something like this:
development:
database: vitae_development
username: rails
...
Then, once database.yml is setup, you'd create the database user (if needed) from inside psql:
psql> create role rails login;
and then let Rails create the database:
$ rake db:create
Then you should be able to run your migrations to create your initial tables and away you go.
You probably want to read the create role documentation to make sure you get the right options. You probably want to be working in the development environment rather than production as well so I changed the names and YAML to reflect that, production is for deployment and I don't think you're deploying anything just yet.
Im'not familiar with rails but you could create your database as a postgres super user and then grant privileges, assuming that in your linux distribution the postgres super user is postgres:
su root
su postgres
createdb vitae_production
then in postgres grant privileges to another user
psql
CREATE USER rails WITH PASSWORD 'myPassword';
GRANT ALL PRIVILEGES ON DATABASE vitae_production TO rails;
ALTER DATABASE vitae_production OWNER TO rails;
then your config file should look like this:
production:
adapter: postgresql
host: localhost
database: vitae_production
pool: 5
timeout: 5000
username: rails
password: myPassword

Resources