Reputation: 1536
This can be beginner thing, but I'm not sure how to deal with it. I want like to add unique constraint to column username
in existing table psql
the migration create table :
class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.integer :user_id
t.string :username
t.string :address
t.timestamps null: true
end
add_index :requests, :user_id
end
end
So I added validation uniqueness in model
class Request < ModelBase
belongs_to :user
validates :user, presence: true
validates :username, uniqueness: true
...
How can I add uniqueness to one column in the database via rails migration?
Upvotes: 4
Views: 9501
Reputation: 1151
To get Ritesh Ranjan's solution using the rails migration generator, try:
rails g migration add_index_to_table_name column_name:uniq
At least in Rails 5.2, this will produce:
class AddIndexToTableName < ActiveRecord::Migration[5.2]
def change
add_column :table_name, :field_name, :string
add_index :table_name, :field_name, unique: true
end
end
You then just have to remove the add_column
statement from the migration.
Upvotes: 2
Reputation: 436
if you want username to be unique, I suggest you to use validation in your app/models/user.rb:
class Request < ApplicationRecord
validates :username, presence:true, uniqueness: {case_sensitive: false}
end
Upvotes: 1
Reputation: 381
def change
remove_column :requests, :user_id
change_column :requests, :username, :string, unique: true
add_reference :requests, :user, index: true
end
Upvotes: 1
Reputation: 1012
At database level, the way you ensure uniqueness is via indexes. In a migration, create a new unique index for the column.
add_index :table_name, :column_name, :unique => true
Or:
rails g migration add_index_to_column_name :column_name, :unique => true
Please note that the creation will fail if you have duplicates in the current database. In that case, first go to the CLI and remove the duplicates, then run the migration.
Upvotes: 7