Alpha Blue 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 
> database.  

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 
> your tables.  

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 
> be incorrect.

Yes.

> 
> 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 AR::Base.

> 
> In the example below, this custom validation is making sure that two 
> fields are identical.
> 
> def self.validates_is_exact(*attr_names)
>   options = attr_names.extract_options!
>   validates_each(*(attr_names << options)) do |record, attr_name, value|
>     if record.send( options[:compare_field] ) != value
>       record.errors.add(attr_name, options[:message])
>     end
>   end
>   true
> end
> 
> 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 
them.

> 
> I hope that helps answer your question.

Best,
--
Marnen Laibow-Koser
http://www.marnen.org
[email protected]
-- 
Posted via http://www.ruby-forum.com/.
-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.


Reply via email to