DR_
DR_

Reputation: 174

Migration with unique column for certain condition?

Can I add uniqueness for a column for a certain condition (on some other column in the table)?

i.e.

add_index :table_name, :column_name1, [:unique => true, where: :column_name2 = false]

Thnx

Upvotes: 1

Views: 757

Answers (1)

Anezio Campos
Anezio Campos

Reputation: 1555

Yes you can but the concept you're doing is wrong.

When you add the unique => true in the table it will ALWAYS validate the uniqueness on database. If it is conditional than you shouldn't do it. On those cases what you need to do is create a validation on the model and not on database, like this:

class Account < ActiveRecord::Base
  validates :email, uniqueness: true
end

You can read more about it here Rails guides

Upvotes: 2

Related Questions