Reputation: 48453
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
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
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
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
Reputation: 7225
see rails doc for method 'establish_connection'
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-establish_connection
Upvotes: 0