Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do i add a ":unique => true" to an already existing reference?

Alan Reid asked in Rails

I have my DB already set up, and it references another table. I need to add in :unique => true so i don't get duplicates. I cant however drop the table and start over as there are items in the DB already.

I know i could do this if i wanted to add a column in to the DB, but what about when it already exists?

rails generate migration add_column_name_to_table_name column_name:references:uniq:index

Which would generate...

class AddIndexToModerators < ActiveRecord::Migration
  def change
    add_reference :table_names, :column_name, index: {:unique=>true}, foreign_key: true
  end
end
Reply

I think that you can use change_column method
change_column(table_name, column_name, type, options = {})
More info

Reply

add_reference :table_name, :column_name, unique: true, foreign_key: true

I think ;)

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.