Friday, December 14, 2007

Rails validates_uniqueness_of(*attr_names) 说明


validates_uniqueness_of(*attr_names)
Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user can be named "davidhh".

class Person < ActiveRecord::Base
validates_uniqueness_of :user_name, :scope => :account_id # 类似account_id, :user_name 组成表中的unique key
end
It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.

class TeacherSchedule < ActiveRecord::Base
validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id] # 类似3个字段组成表的unique key
end

No comments :