pic*_*rdo 4 validation activerecord mongoid ruby-on-rails-3
我想知道我是否可以编写验证来验证基于多个字段的记录的唯一性.我的模型有一个复合主键,即
field :houseno, :type => String
field :street, :type => String
field :boro, :type => String
什么是验证此记录的唯一性的好方法?
我正在尝试使用这样的自定义验证器:
class AddressValidator < ActiveModel::Validator
  def validate(record)
    record.errors[:base] << "This address is already in our records." unless check(record)
  end
  private
    def check(record)
      Address.find(:street=>record.street,:houseno=>record.houseno,:boro=>record.boro).length > 0
    end
end
TK-*_*421 12
你需要使用scope:
validates :houseno, uniqueness: { scope: [:street, :boro] }
| 归档时间: | 
 | 
| 查看次数: | 3242 次 | 
| 最近记录: |