简体   繁体   中英

How to Generate Rails App Models & Migrations for Legacy SQL Server Database?

I'm having trouble creating models in my RoR application for preexisting tables in my sql server database.

In ruby console when I type: ActiveRecord::Base.connection.tables , the following is returned: ["Bank", "Owner", "Location", "Zone"].

The above is returned without any models or migrations having been created in the app. So the next step is to create a model...

rails g model Bank

And edit the model:

class Bank < ActiveRecord::Base
    set_table_name = "Bank"
    set_primary_key "BankID"
end

And edit the migration:

class CreateBanks < ActiveRecord::Migration
  def change
    create_table "Master.Bank" do |t| // Because Bank is in the 'Master' schema, not the default 'dbo'

      t.timestamps
    end
  end
end

The edits to the model and migration file I have come to understand from my own research should allow me to successfully link a model in my app to a legacy database with table names that do not match Rails' conventions and in the appropriate schema.

However, after doing all this, the command rake db:migrate generates the error, "TinyTds::Error: There is already an object named 'Bank' in the database."

What am I doing wrong?

As you are creating from a legacy DB, you don't know the migrations, as the tables already exist. Rails should introspect the table and generate the correct fields. Just make sure that the default schema for the user you are accessing the database with is the schema that owns the tables.

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