I'd like to know if I can write a validation that would validate the uniqueness of a record based on multiple fields. My model has a composite primary key, i.e.
field :houseno, :type => String
field :street, :type => String
field :boro, :type => String
What would be a good way of validating the uniqueness of this record?
I'm trying to use custom validators like this:
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
You need to use scope
:
validates :houseno, uniqueness: { scope: [:street, :boro] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With