简体   繁体   中英

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?

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 :).

First you have to setup your application to user sql server for databases connectivity. you have to use gem for sql server in your gemfile and have to setup database.yml file accordingly.

In database.yml , in config folder put the name of same database In the Development part of this file.

    development:
  adapter: 
  database: db_name_dev
  username: 
  password:
  host: localhost
  socket:

To use a existing server. In your database.yml you have to specify the host, port and the database name.

`database: <host>:<port>/<database_name>`

For eg

development:
  adapter: mysql2
  database: your.mysqlserver.com:1521/project_database
  username: project_user
  password: project_password

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM