Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using existing SQL Server database with Ruby on Rails

I'm on the early stages on learning Ruby.I really don't have an idea on how to use an existing database filled with tables and data on ruby. Every guide, every article that I have or find on the internet is always creating a new one using the migration functions.

But which are the steps for using an existing database in SQL server on RoR?

like image 754
divz Avatar asked Jun 05 '26 11:06

divz


1 Answers

You're in luck, friend. My first Rails project (7 years ago) was against a horribly set up SQL Server database.

Per the above, you need to set up your database.yml appropriately. But for an existing database, obviously it is unlikely that the table and column names conform to the Rails conventions. The good news is that you can override all of those defaults. Here is a non-exhaustive list of those directives:

In a model descended from AR::Base,

set_table_name 'actual_table_name'
set_primary_key 'actual_primary_key_name'

On the various association directives (has_one, has_many, belongs_to), there are :foreign_key keys that let you specify the name of the foreign keys.

Now, one of the things that MS SQL Server allows you to do which is TERRIBLE is that you can embed spaces into your column names. Fear not, you can still refer to these columns by name using write_attribute("badly named column") and read_attribute("badly named column"). You may also refer to them in various directives like so:

validates_length_of "Fax Number", :maximum => 17, :allow_nil => true

Finally, you may refer to the implied methods these devilishly named columns generate like so:

self.send('Fax Number=', new_fax_number)

Obviously, you can't refer to them as symbols, since spaces are disallowed in Ruby symbols.

Good luck, and next time I hope that you get to work with a real RDBMS, like Informix :).

like image 124
Wes Gamble Avatar answered Jun 06 '26 23:06

Wes Gamble