Reputation: 4320
I have this models:
class Ofert < ActiveRecord::Base
belongs_to :user
validates_uniqueness_of :reference, scope: :user_id
end
class User < ActiveRecord::Base
has_many :oferts
end
I want to validate the uniqueness of the attribute reference
scoped by user_id
, I mean, the same user can't have a product with the same reference, but the reference can be repeated if it's not the same user.
as you can see there is a validates_uniqueness_of
statement in the Ofert
model, then I added this migration:
add_index(:oferts, [:reference, :user_id], unique: true)
However when I run the migration I get the following error:
Mysql2::Error: BLOB/TEXT column 'reference' used in key specification without a key length: CREATE UNIQUE INDEX `index_oferts_on_reference_and_user_id` ON `oferts` (`reference`, `user_id`)
What's wrong here?
Upvotes: 1
Views: 435
Reputation: 24337
Since :reference is a text or blob column, you must specify a length for the index:
add_index :oferts, [:reference, :user_id], unique: true, length: 10
There are maximum length limits that depend on the database engine you are using, so double check the MySQL index documentation.
Upvotes: 2