将主键定义转储到schema.rb中

时间:2015-01-29 15:05:43

标签: mysql ruby-on-rails primary-key

我正在使用Rails 4和MySQL,而我目前正试图使我的应用程序代码(以前用Rails和MySQL编写)更加数据库无关(将MySQL触发器重写为Rails回调) ,存储过程作为Rails方法等),以便我可以移动到不同的数据库,如PostgreSQL或MongoDB。现在我试图从Rails内部正确定义表,而不是以任何方式使用MySQL。所以在我的一次迁移中我有

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

当我运行此迁移并使用MySQL Workbench检查表时,表格已正确创建并且" Brand"被定义为主键。但是,当我立即检查生成的schema.rb文件或运行rake db:schema:dump之后,我没有看到" Brand"作为主键:

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

我对此感到担心,因为我计划稍后使用rake db:schema:load从schema.rb文件在另一台计算机上生成数据库,而不是运行所有迁移。有没有什么方法可以确保主键被正确地转储到schema.rb而不是手动编辑文件?

我使用的是Ruby 2.1.5和Rails 4.1.8。

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用https://github.com/vprokopchuk256/mv-core gem重写验证/约束?

我允许您以与数据库无关的方式编写验证。有MySQL,PostgreSQL,SQLite

的驱动程序

示例:

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

此类验证将转储到schema.rb。

您可以根据自己的模型对事件进行升级:

class Brand < ActiveRecord::Base
  enforce_migration_validations
end
相关问题