ActiveRecord: When / where to validate data? Tricky question


First of all, thanks for you time. I have kind of a tricky question and
wanted to see what you guys thought.

Lets say I have this:

class Purchase < ActiveRecord::Base
validates_numericality_of :some_number, :only_integer => true

Then I do this:

purchase =
purchase.some_number = ‘This is not a number’

Right now the data is not correct. Is this ok? Why should I even let
invalid data like this get put into the some_number attribute? So my
question is this…

Is this better?

Instead of doing:
validates_numericality_of :some_number, :only_integer => true

Doesn’t it make more sense to validate the data as it’s being set and if
it’s not correct raise an exception? This way its not even possible to
get valid data into this attribute, which renders the statement
(validates_numericality_of :some_number, :only_integer => true)

If you dig deeper I guess the real question is, will I ever use
purchase.some_number when its not pulled directly out of the db?

Any help is greatly appreciated.


Hi Ben,

I think you make some good points, but I also think that the style of
programming rails would need to change a lot for this to work.

for eg if what your suggesting occurs I could not, in response to a form
do params[:my_model] )
without wrapping it in a begin rescue, which isn’t that bad, but…

In my view template I could no longer call error_messages_for and get a
list of errors to feed back to the user since it would stop processing
validation as soon as one failed.

Similarly what would happen with
@my_model.update_attributes( params[:my_model]) ? My guess is

I don’t think I would like this.

Having said that if you wanted to do this you could roll your own as a