简体   繁体   中英

dump primary key definition into schema.rb

I'm using Rails 4 with MySQL, and I'm currently trying to make my application's code (previously written in Rails and MySQL) more database-agnostic (rewriting MySQL triggers as Rails callbacks, stored procedures as Rails methods, etc.) so that I can possibly move to a different database, such as PostgreSQL or MongoDB. Right now I'm trying to define the tables properly from inside Rails, without using MySQL in any way. So in one of my migrations I have

create_table :brands, {id: false, primary_key: :Brand} do |t|
    t.string :Brand, limit: 30, null: false
    t.timestamps
end

add_index :brands, :Brand, unique: true

When I run this migration and check the table using MySQL Workbench, the table is created properly and "Brand" is defined as the primary key. However, when I check the generated schema.rb file immediately or after running rake db:schema:dump , I see no mention of "Brand" being a primary key:

create_table "brands", id: false, force: true do |t|
    t.string   "Brand",      limit: 30, null: false
    t.datetime "created_at"
    t.datetime "updated_at"
end

add_index "brands", ["Brand"], name: "index_brands_on_Brand", unique: true, using: :btree

I'm concerned about this because I am planning on later generating the database on another machine from the schema.rb file using rake db:schema:load , instead of running all the migrations. Is there any way that I can ensure that primary keys are dumped to schema.rb correctly instead of editing the file manually?

I'm using Ruby 2.1.5 and Rails 4.1.8.

Have you considered to rewrite your validations / constraints using https://github.com/vprokopchuk256/mv-core gem?

I allows you to write validations in a db - agnostic way. There are drivers for MySQL, PostgreSQL, SQLite

Example:

create_table "brands", id: false, force: true do |t|
  t.string   "Brand",      limit: 30, null: false, 
                           uniqueness: true, length: 1..30
  t.datetime "created_at"
  t.datetime "updated_at"
end

Such validations will be dumped to schema.rb.

You can event level them up to you model:

class Brand < ActiveRecord::Base
  enforce_migration_validations
end

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