181

I use Rails 3.0.0.beta4

I want to add a validation on uniqueness on two attributes, that means that my model is valid if the couple of 'recorded_at' and 'zipcode' is unique.

On one attribute here is the syntax

validates :zipcode, :uniqueness => true

thanks

denisjacquemin
  • 7,414
  • 10
  • 55
  • 72

3 Answers3

343

In Rails 2, I would have written:

validates_uniqueness_of :zipcode, :scope => :recorded_at

In Rails 3:

validates :zipcode, :uniqueness => {:scope => :recorded_at}

For multiple attributes:

validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}
Jason Swett
  • 43,526
  • 67
  • 220
  • 351
Christian Lescuyer
  • 18,893
  • 5
  • 49
  • 45
  • 8
    I would say that logically it makes more sense to say that you require `recorded_at` to be unique within the scope of a zipcode. `validate :recorded_at, : uniqueness => { :scope => :zipcode }` – Ariejan Jul 29 '10 at 08:41
  • 2
    you can still do it the rails 2 way, and I find that more readable unless you're doing several types of validation on the same property. – zem Jul 03 '11 at 23:29
  • 25
    would you validate a group of three with `validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}`? – Greg Guida Jul 13 '12 at 21:39
  • 6
    I would add that if you want to use `:scope` on foreign keys, you need to use the `:fkey_id` symbols, instead of `:fkey` ones, even if a "basic" `:uniqueness` works on `:fkey` – nbarraille Sep 07 '12 at 02:48
  • 1
    You probably want to add a custom error msg like `, :message => ' is taken for this recorded date'` – laffuste May 15 '14 at 09:01
  • How to add `allow_nil: true` to multiple scope arguments? For example, in above case, how to make `:recorded_at and :something_else` `allow_nil: true` – mrudult Feb 19 '16 at 10:51
  • Rails 6.1 `validates :year_date, uniqueness: {scope: [:person_id, :location_id], message: '. Already an item for this person at this address on this date'}` – Greg Dec 23 '20 at 20:15
99

Multiple Scope Parameters:

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

This should answer Greg's question.

Ray
  • 1,161
  • 7
  • 11
  • Greg seemed more interested in using the 'validates' shortcut, so a quicker answer to his question is "yes" – elc Sep 28 '12 at 00:04
  • This is quite important to know, I was looking exactly to this if I should use the _id (or not) when checking for associations in scopes. – Francesco Belladonna Aug 01 '13 at 22:45
  • This answer works in Rails 4.1.6 validates_uniqueness_of :cart_id, scope: [:location_id, :plug_id] – Conor Jan 28 '15 at 08:24
6

Dont work for me, need to put scope in plural

validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]

Jesus
  • 752
  • 7
  • 5