Rails use MS SQL server database

2020-07-14 06:02发布

问题:

In my rails app, I need to use an existing MS SQL database. I have tried following this manual:

http://rubyrailsandwindows.blogspot.com/2008/03/rails-2-and-sql-server-2008-on-windows_24.html

I do not know how to do models, scaffolds, etc because rails cannot simply use another db. I didn't want to run rake db:migrate for my tables in the MS SQL database. What else do I need to write in the model? If simple: use tables from the MS SQL server's database, but I also want to solve problem with migrations, etc.

回答1:

If you need to run your Rails up on top of the existing database and you want to make sure you can create all models that match existing tables, follow this guide:

  • Dump the schema into schema.rb using http://guides.rubyonrails.org/migrations.html#schema-dumping-and-you. I would actually use SQL mode of schema (config.active_record.schema_format = :sql ) and just use SQL Server tools to generate SQL file of the database schema and preserve it as db/structure.sql
  • After the database schema has been established, you can redirect tables and primary keys in your models using an approach outlined here: Putting Rails over top of an existing database

As an alternative to ActiveRecord altogether, you might consider DataMapper as it claims to work better with "brownfield" (i.e. already established) databases.