views:

58

answers:

5

My models produce a lot of values for attributes which the user can not specify in any forms.

Should I be specifying validations for those attributes to prevent any of my model logic creating dodgy values or is that something I should just check for in my tests?

A: 

Validation is for sanitizing user input.

Myles
+1  A: 

It depends on what values the model is producing. If it is producing values depending on the user input, then yes validate them. Otherwise this is something you should check in your tests.

+2  A: 

As well as being essential for confirming user input, Active Record validations also provide a useful DSL for specifying the intent behind your domain design.

Toby Hede
+1  A: 

In relation to ActiveRecord. Any attribute that has a corresponding column in the database (and would ultimately be used to populate that column) and requires a specific level of continuity/integrity should be validated.

Ex: if an attribute requires the data it accepts falls between a range of 1..10 then you probably want to validate that the data set for that attribute meets those requirements.

You should always test, well, usually. But, if the code is of your own design then you should test it.

-

*Also, please do not confuse Validation for Sanitization, or vice versa, at least in their traditional roles. Just because you sanitize something does not mean it's valid.

If you sanitize ABCD so it does not contain <script> but your database column only accepts integers, ABCD is not exactly "valid", though it may have been sanitized.

nowk
+1  A: 

Since the model represents the data of your system, you should specify constraints on that data. Since Ruby is a dynamic interpreted language, all constraints are validated at run-time, every time you create, update, or delete an ActiveRecord object.

It is a good practice to have explicit constraints on all attributes of a model class, whether they correspond to database fields or not. Quite often, the data from your model will drive the behaviour of your controller and the rendering of your views, and it would be a shame (and possibly an exception) if the accessible data did not for some reason fall within a constraint.

You should, of course, test all of these validation functions as a part of your system testing.

The fact that you are worried about "dodgy" values suggests to me that your data is not properly normalized. I suggest you read up on the various normal forms, and try to design your data schemas to at least third normal form. That should help you get rid of the possibility of having "dodgy" model attributes.

Jay Godse