While reading the Rails Guides, I came across something I’m unsure about. In the example, it shows that I can write a scope option that adds additional options towards checking uniqueness. My questions is, do I have to write out a method that queries specifically towards a time period. In other words, is there more code necessary than meets the eye in the example below? If not, how does Rails knows to check the right time stamp column in the table database?
class Holiday < ActiveRecord::Base
validates :name,
:uniqueness => { :scope => :year,
:message => "should happen once per year" }
end
All this does is ensure uniqueness in the context of a
yearcolumn on your model – that column can be anything, but it needs to exist. It will not automagically check the year part of timestamp with a full date. Your model is responsible for actually storing theyearvalue.You can of course populate this
yearautomatically. Let’s say you have a columnholiday_datein your model. Then you can ensure that theyearcolumn is always set like so:(The
trymethods just ensures that there’s no error ifholiday_datehappens to benil)