How to Use Activerecord in a Ruby Script Outside Rails

How to use ActiveRecord in a ruby script outside Rails?

require 'active_record'

# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'mysql2', # or 'postgresql' or 'sqlite3' or 'oracle_enhanced'
host: 'localhost',
database: 'your_database',
username: 'your_username',
password: 'your_password'
)

# Define your classes based on the database, as always
class SomeClass < ActiveRecord::Base
#blah, blah, blah
end

# Now do stuff with it
puts SomeClass.find :all
some_class = SomeClass.new

How to use ActiveRecord in a JRuby script outside Rails?

Change your require to:

require 'active_record'

How to use ActiveRecord for Multiple Environment outside Rails?

What rails does may look like magic, but it's actually very simple (well, this case, at least). Here's the outline:

At startup, app loads all available database configurations. By convention, they are stored in YAML format in config/database.yml.

Then, current environment is determined. The easiest way to do this is environment variables. For example:

 MY_ENV=production ruby my_script.rb

Then, in the script, you fetch current env, pick corresponding connection configuration and use it to connect.

connection_configs = YAML.load(File.read('config/database.yml'))
current_env = ENV['MY_ENV'] || 'development' # if no value, assume development mode
ActiveRecord::Base.establish_connection(connection_configs[current_env])

How can I use existing Activerecord model in rails in ruby script

There are two common ways to deal with Rails models from the command line:

1) rake tasks

Create a rake task in lib/tasks

# example lib/tasks/foo.rake
desc 'an example task'
task :foo => [:environment] do
user = User.new
...
end

And call that task from your command line with:

rake foo

2) script runner

Create a method within your application that does the job

# example in app/models/user.rb
class User < ActiveRecord::Base
...
def self.foo
user = User.new
...
end
end

And call this method from the command line with:

rails runner "User.foo"

I prefer the second way, because it is easier to test and reuse the code.

include a model class outside rails

require 'active_record'
require 'mysql2'

require 'path/to/class.rb'

ActiveRecord::Base.establish_connection(
adapter: 'mysql2', # or 'postgresql' or 'sqlite3'
...

how to require active record working outside of rails

Here's how I'm using ActiveRecord outside of Rails:

#!/usr/bin/ruby

require 'active_record'
require 'mysql2' # or 'pg' or 'sqlite3'

ActiveRecord::Base.establish_connection(
adapter: 'mysql2', # or 'postgresql' or 'sqlite3'
database: 'DB_NAME',
username: 'DB_USER',
password: 'DB_PASS',
host: 'localhost'
)

# Note that the corresponding table is 'orders'
class Order < ActiveRecord::Base
end

Order.all.each do |o|
puts "o: #{o.inspect}"
end


Related Topics



Leave a reply



Submit