How do I make a column unique and index it in a Ruby on Rails migration?

I would like to make a column unique in Ruby on Rails migration script. What is the best way to do it? Also is there a way to index a column in a table?

I would like to enforce unique columns in a database as opposed to just using :validate_uniqueness_of .


The short answer:

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

For finer grained control, there's a " execute " method that executes straight SQL.

That's it!

If you are doing this as a replacement for regular old model validations, just check to see how it works. I'm not sure the error reporting to the user will be as nice. You can always do both.


rails generate migration add_index_to_table_name column_name:uniq

or

rails generate migration add_column_name_to_table_name column_name:string:uniq:index

generates

class AddIndexToModerators < ActiveRecord::Migration
  def change
    add_column :moderators, :username, :string
    add_index :moderators, :username, unique: true
  end
end

If you're adding an index to an existing column, remove or comment the add_column line, or put in a check

add_column :moderators, :username, :string unless column_exists? :moderators, :username

Since this hasn't been mentioned yet but answers the question I had when I found this page, you can also specify that an index should be unique when adding it via t.references or t.belongs_to :

create_table :accounts do |t|
  t.references :user, index: { unique: true } # or t.belongs_to

  # other columns...
end

(as of at least Rails 4.2.7 )

链接地址: http://www.djcxy.com/p/47176.html

上一篇: Rails迁移更改列

下一篇: 如何在Ruby on Rails迁移中创建唯一的列并将其编入索引?