TopperH
TopperH

Reputation: 2223

Validate against duplicate fields in same record

I have a model that has three fields called:

I want to prevent users from using the same value in more than one field. I do not want to validate uniqueness against other records or scopes, just within the present record.

The failing test looks like this:

expect(build(:post, url1: "foo", url2: "foo").to_not be_valid

Does activerecord provide a validation for this scenario or should I write my own?

EDIT:

Following Nermin suggestion I created my own validator. I needed to add some logic since I'm allowing strings to be blank but obviously I don't want blanks compared to return false positives.

  validate :unique_urls_on_post

  def unique_urls_on_post
    #avoid duplicate url but still allow blank
    my_array = []
    [iurl1, url2, url3].each do |i| 
      my_array << i unless i.length < 1 #empty string don't go in the array
    end 
    unless my_array.uniq.length == my_array.count
      errors.add(:url1, "has to be unique")
      errors.add(:url2, "has to be unique")
      errors.add(:url3, "has to be unique")
      false
    end 
  end 

Upvotes: 0

Views: 760

Answers (2)

Nermin
Nermin

Reputation: 6100

You can create custom validation

validate :unique_url_on_user

...
def unique_url_on_user
  unless url1 != url2 != url3
    errors.add(:url2, "has to be unique") # or any kind of message
    false
  end
end

Upvotes: 1

Miotsu
Miotsu

Reputation: 1776

As you can see on the official guide (http://guides.rubyonrails.org/active_record_validations.html)

there is no specific validation helper for this task, you'll have to write your own validation method.

Upvotes: 0

Related Questions