Unique on three different fields
I am working on a Ruby on Rails web application. I want to validate the uniqueness of more than one field together. How can i do this?
For example: I have a model named waiting
with t开发者_运维百科hree fields:
project_id
category_id
and user_id
I want to ensure that i won't have two identical rows in all three fields.
Why not just to:
validates_uniqueness_of :user_id, :scope => [:project_id, :category_id]
+
add_index :waitings, [:project_id, :category_id, :user_id], :unique => true
Read API:
- http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_uniqueness_of
- http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index
It's not pretty but this works for me:
class Waiting < ActiveRecord::Base
validate :must_be_unique
def must_be_unique
if self.class.where(project_id: project_id, category_id: category_id, user_id: user_id).exists?
errors.add(:base, 'Must be unique')
end
end
end
Of course you could just use a unique key in your db schema and then catch the relevant exceptions on the rare occasion you need to.
精彩评论