rails 3 validation on uniqueness on multiple attributes

Ruby on-RailsValidation

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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]}

Solution 2 - Ruby on-Rails

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.

Solution 3 - Ruby on-Rails

Dont work for me, need to put scope in plural

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondenisjacqueminView Question on Stackoverflow
Solution 1 - Ruby on-RailsChristian LescuyerView Answer on Stackoverflow
Solution 2 - Ruby on-RailsRayView Answer on Stackoverflow
Solution 3 - Ruby on-RailsJesusView Answer on Stackoverflow