Skip to main content

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

Rails • Asked by Alan Reid

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

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


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

I think ;)


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.