我想知道在Rails 3中是否有一种方法,我可以在其中验证组合的2个字段的唯一性。
逻辑就是这样:
我有两个字段employee_code
和date_entry
。
案例1:如果employee_code
和date_entry
组合已存在,则不允许保存具有相同employee_code
和date_entry
的其他记录。< / p>
案例2:如果employee_code
和date_entry
存在但不在同一记录中,则可以保存该字段。
答案 0 :(得分:35)
validates_uniqueness_of :employee_code, :scope => [:date_entry]
三列甚至更多列,您只需要在范围列表中添加元素:
validates_uniqueness_of :employee_code, :scope => [:date_entry, :another_column]
或Rails 3:
validates :employee_code, :uniqueness => {:scope => :date_entry}
答案 1 :(得分:13)
这适用于Rails 3:
要仅使用2列进行此操作,您可以执行以下操作:
验证:empcode,:uniqueness =&gt; {:scope =&gt; :date_entry}
对于超过2列,您可以执行以下操作:
验证:empcode,:uniqueness =&gt; {:scope =&gt; [:date_entry,:description]}