user984621
user984621

Reputation: 48453

How to connect to database from script in /lib dir?

I have a script in lib directory and I need to fetch some data.

require 'active_record'

Article.each do ...

When I try this, I got this error message:

file.rb:3:in `<main>': uninitialized constant Article (NameError)

How can I load data from Rails database and display them in a raw ruby script?

Upvotes: 1

Views: 1493

Answers (4)

toro2k
toro2k

Reputation: 19228

You could use the command rails runner lib/your_script.rb, from the Rails application root directory, to execute your script. It will execute the script after loading the Rails environment, so in the script you have full access to your models.

Upvotes: 2

sunny1304
sunny1304

Reputation: 1694

This will help you to connect your db with active record: http://www.runtime-era.com/2012/11/dynamic-activerecord-database.html

Upvotes: -1

Yevgeniy Anfilofyev
Yevgeniy Anfilofyev

Reputation: 4847

In your script you should add adapter, something like this:

require 'active_record'
require 'sqlite3'

ActiveRecord::Base.establish_connection(
   :adapter => 'sqlite3',
   :database => 'db/yourDb.db'
)

And model(s), like this:

require_relative 'path to your model(s) file(s)'

Upvotes: 1

Sachin Singh
Sachin Singh

Reputation: 7225

see rails doc for method 'establish_connection'

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-establish_connection

Upvotes: 0

Related Questions