Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniqueness with scope in migration

I've been trying to find a way to achieve this but I cannot find any attempts even so I am thinking that maybe my approach is completely wrong. That said, what should I do in my migration if I want a combination of two fields to be unique? Please note that I do not want them to be indexes, just database fields.

For example, for the migration below, I can separately add unique: true to the fields, but the combo?

class CreateSomething < ActiveRecord::Migration
  def change
    create_table :something do |t|
      t.date :datestamp, :null => false
      t.integer :some_number, :null => false
      t.timestamps
    end
  end
end
like image 760
sebkkom Avatar asked Oct 08 '14 16:10

sebkkom


1 Answers

I'm not sure what you mean by

Please note that I do not want them to be indexes, just database fields.

Indexes are extra pieces on information that the database stores about the columns. More importantly an index is exactly what you need!

class CreateSomething < ActiveRecord::Migration
  def change
    create_table :something do |t|
      t.date :datestamp, :null => false
      t.integer :some_number, :null => false
      t.timestamps
    end
    add_index :something, [:datestamp, :some_number], unique: true
  end
end
like image 67
Nikolai B Avatar answered Nov 15 '22 18:11

Nikolai B