Azarantara
Azarantara

Reputation: 537

Accessing a database through Rails model from a seperate Ruby script

I have a Rails application with a database (PostgreSQL using ActiveRecord)

In a separate directory on the same server I have a Ruby script.

How can I, from the Ruby script, reach the Rails database through one of my Rails models?


I have seen that it is possible to require ActiveRecord and pass in the database details, but from what I understand I would need to rebuild the model, which means a lot of repetition of validations, methods, etc. Instead I'd like to somehow use the model that's already in place.

Upvotes: 2

Views: 833

Answers (3)

Phil
Phil

Reputation: 2807

Try using rails runner. According to: http://guides.rubyonrails.org/command_line.html#rails-runner

runner runs Ruby code in the context of Rails non-interactively. For instance:

bin/rails runner "Model.long_running_method"

In my experience this works nicely to run scripts that rely on Active Record and more.

Add the -e switch to the command to force the use of your production database connection:

bin/rails runner -e staging "Model.long_running_method" 

Add any other environment variables that may be required to complete the database connection. If you use the Devise gem, you will also need to pass in a secret to allow the Devise initializations to complete. Other gems may equally need some assistance to get started.

Upvotes: 1

Azarantara
Azarantara

Reputation: 537

I found a solution that has the behaviour I was looking for, and am posting it as an answer for anyone who comes across this question at a later date.

Setting ENV['RAILS_ENV'] = "production" and then simply requiring the environment.rb file (with the appropriate path) in the Ruby script solves the issue very nicely.

This is similar to the answer provided by @MurifoX, but saves you having to re-declare the DB connection.

Upvotes: 2

MurifoX
MurifoX

Reputation: 15099

You can use require to pass the relative path to your model, and then instatiate it a use.

require '/path/to/your/model/inside/your/app'

model = Model.new 

For the connection, if you are using postgresql, you can use the PGconn class from the pg gem like this:

@connection = PGconn.open(
  :user => 'postgres', 
  :password => 'password', 
  :host => 'host', 
  :dbname => 'dbname')

Upvotes: 0

Related Questions