简体   繁体   中英

schema.rb does not include :unique on add_index

I have the following migration:

class UniqueIndexOnCustomValueKeys < ActiveRecord::Migration
  def self.up
    add_index :custom_values, [:customizable_id, :customizable_type, :custom_definition_id], {:unique=>true,:name=>:cv_unique_composite} 
  end

  def self.down
    remove_index :custom_values, :cv_unique_composite
  end
end

When I run the migration, it creates the UNIQUE key properly in the development database, but when I look at schema.rb , the :unique flag isn't there. This is causing the test database to not have the UNIQUE index.

The resulting line in schema.rb looks like:

add_index "custom_values", ["customizable_id", "customizable_type", "custom_definition_id"], :name => "cv_unique_composite"

Am I doing something wrong here?

(Rails 3.0.8, MySql2 gem)

尝试这个为自己。

add_index :custom_values, [:customizable_id, :customizable_type, :custom_definition_id], unique: true, name: 'cv_unique_composite'

In order to accommodate unique indexes, you need to change the active_record.schema_format in application.rb:

config.active_record.schema_format = :sql

This will force the test database to use db/development_structure.sql which takes raw sql statements from the database instead of ruby commands.

This question addresses Oracle, but the same issue exists for other database specific issues (In this case MySql Unique Indexes): Why am I not getting any index defintions in my Rails schema.db - "# unrecognized index ..."

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