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

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

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 ;)

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.