In Ruby on Rails there are two ways to validate, for instance, the presence
of input fields. Say I want to make sure the user has filled out my fields called value
and name
. I could put in my model either:
validates_presence_of :value, :name
## Or
validates :value, presence: true
validates :name, presence: true
In this situation judging strictly by DRYness, method 1 looks better, but in the application I'm working on I have the following validation:
validates_presence_of :value, :name
validates_uniqueness_of :value
validates_numericality_of :value, :only_integer => true
## Which I can refactor to:
validates :value, presence: true, uniqueness: true, numericality: { only_integer: true }
validates :name, presence: true
And in this case the second method looks better.
- Is there a generally preferred method, or is it case-by-case? (If it's case-by-case, wouldn't it be confusing for maintainers?)
- Is it safe to adopt one method for the entire application? (If so, which one should I adopt?)