Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate models with a composite keys in ActiveRecord?

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
like image 501
picardo Avatar asked Dec 16 '22 18:12

picardo


1 Answers

You need to use scope:

validates :houseno, uniqueness: { scope: [:street, :boro] }
like image 172
TK-421 Avatar answered May 20 '23 10:05

TK-421