Alpha B. wrote:
I have to agree with both Marnen and Rob here.
First, validations are not meant to make a user happy. It’s to ensure
that proper validation is met before data is inserted into your
Not really. Validations are meant to make users happy, sort of. The
database should have its own check and key constraints so that invalid
data can never make it in there.
App-layer validations exist so that the app UI can be better and so that
complex constraints that are impractical to put in the DB are possible
(such as e-mail regex validation?).
Therefore, the more accurate you validate your forms, the
least likely you are to have some type of data corruption occur within
No! You must not rely solely on Rails validations to prevent your
database from getting corrupted.
It is much easier to review all of the validations taking
place than to specify for specific entries because more than one could
Second, you can definitely write your own validations but keep some
things in mind when you do so. If you are going to reuse the validation
(most likely you are) place it in your initializers so that your
environment remains clean and you also can reuse the validator at some
point in time.
Again, no. Put it in a module or something, same as you would any other
AR class method.
I have the following custom validator located in validators.rb in my
config -> initialize folder.
That should be in a module, probably in your lib folder. You could call
it from a plugin, or use environment.rb or an initializer to include it
In the example below, this custom validation is making sure that two
fields are identical.
options = attr_names.extract_options!
validates_each((attr_names << options)) do |record, attr_name, value|
if record.send( options[:compare_field] ) != value
validates_is_exact :field_one, :compare_field => :field_two
Bad example. The only time you should ever need to do this is in the
case already covered by validates_confirmation_of. If you have two
fields in the DB that should always be identical, then remove one of
I hope that helps answer your question.