ylluminate
ylluminate

Reputation: 12369

How to incorporate a Rails 3.1.x database into a standard ruby app via ActiveRecord?

I have a Rails 3.1.x app and need to manipulate the data in it's database via another straight ruby app. Essentially I am just retrieving data from a model in the database.

Obviously it would start off with something like:

require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter => 'mysql2',
  :encoding => 'utf8',
  :database => 'database_name',
  :username => 'username',
  :password => 'password',
  :host => 'hostname'
)

But where do I go from here with models already set up? Do I import the schema.rb or models?

Would appreciate a more comprehensive use case example of getting a db used in Rails into a standard ruby script.

Upvotes: 1

Views: 141

Answers (3)

TomDunning
TomDunning

Reputation: 4877

I've done this before, 1 x Sinatra app and 5 x rails apps.

However my approach requires git and git submodule.

Move the /models dir into a new project with its own repo.

Require that project as a submodule (mapped to /models) within each app which wants to use it. This then means that you only ever need to edit one version of the models to update all applications which use them.

GitHub has a pretty good guide on submodule: http://help.github.com/submodules/

Upvotes: 1

the Tin Man
the Tin Man

Reputation: 160551

Rails has rake and script/runner. Both can make it easy to access your models and transparently connect to the database.

I've used script/runner when I was retrieving data files from a remote host and needed to insert it into my database underneath the Rails front-end. It worked very nicely.

Read through some of these Stack Overflow questions for more info:

Upvotes: 1

tadman
tadman

Reputation: 211560

You'll need the model files. The schema.rb is only relevant if you'll be using migrations and it's probably a bad idea to split those across two different applications. Use your Rails app as your master and your new Ruby app as a dependent application.

Just be sure that if your models have any dependencies those are included as well.

In some instances it might be easier to create another directory in your Rails repository for hosting this other Ruby application if they are sufficiently tied together.

Upvotes: 1

Related Questions