Ruby on Rails 3, Sequel, Tapping into an existing database

1.1k views Asked by At

How does one use Rails 3 to read data from tables in an existing database that does not match the Rails 3 standard schema?

I've been told the Sequel gem is a good place to start, but I don't have much beyond that.

Specifics:

  • It's an Oracle database. I've already established connectivity, and have confirmed that migrations and rollbacks work properly.
  • I've generated scaffolds for the needed tables and the relevant columns.
  • I am looking for a way to specify and map the relevant tables and columns.
  • Can this be done without Sequel?
1

There are 1 answers

0
the Tin Man On

Sequel is an excellent gem for this. It's my first choice when I'm dealing with legacy databases.

Its an Oracle database. I've already established connectivity, and have confirmed that migrations and rollbacks work properly.

If your database is in an enterprise and is in production, and is being used by other apps, you need to be very careful using migrations. I'd recommend only using them if you are responsible for the database development too, and even then I'd be careful.

I've generated scaffolds for the needed tables and the relevant columns.

By scaffolds, do you mean forms?

I am looking for a way to specify and map the relevant tables and columns.

Sequel is very flexible and lets you use raw SQL, use models, or work between the two. If you have a table named "spoons" and have connected to it:

DB[:spoons]

will create a dataset to access the table. From there you can append where clauses, selects, ordering, etc.

An alternate way is to use models, similar to ActiveRecord:

class Spoon < Sequel:Model
end

which creates a model of the table's records with accessors for all the fields.

Sequel makes assumptions about the primary index name "id", like ActiveRecord, but you can change it if need be.

Either method is very powerful and works well with databases using autodiscovery of the fields and their types.

The README is a very good overview of what you need to know.

Also, Jeremy Evans is the developer and is very responsive if you ask him technical questions.

Can this be done without Sequel?

Of course. ActiveRecord will work using models, but you might have to tell it the names of keys or tables if they don't meet its predetermined/expected names.