Validates_uniqueness_of with :scope
Posted on June 01, 2007 at 02:20 PM
If you a trying to validate if the value of an attribute is unique on the database, you can easily accomplish this by using the built in helper method…
validates_uniqueness_ofBut how would you go about making sure the attribute value is unique based on a scope parameter? Let’s say you are building a holidays table and need to make sure you only allow one ‘Christmas’ holiday to be created per year:
validates_uniqueness_of :name, :scope => :year, :message => "must be unique"
Hope that helps!
Comments
There are 2 comments on this post. Post yours →
What if you wanted to make the database entry unique in terms of the past 30 days?
Say, you can’t schedule a happy hour more than once a month.
Can this be achieved using :scope?
Thanks,
RPR
Helps a lot, thanks !
Post a comment
Required fields in bold.