如果我想检查是否存在2字段组合,如何验证Rails 3模型中的唯一性?

时间:2011-03-31 02:17:25

标签: ruby-on-rails-3 model

我想知道在Rails 3中是否有一种方法,我可以在其中验证组合的2个字段的唯一性。

逻辑就是这样:

我有两个字段employee_codedate_entry

  • 案例1:如果employee_codedate_entry组合已存在,则不允许保存具有相同employee_codedate_entry的其他记录。< / p>

  • 案例2:如果employee_codedate_entry存在但不在同一记录中,则可以保存该字段。

2 个答案:

答案 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]}