Forum: Ruby on Rails ActiveRecord: When / where to validate data? Tricky question

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
328f0bb678423fcea01ebe3b0edc74e6?d=identicon&s=25 Ben Johnson (benjohnson)
on 2006-06-01 00:06
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.
9d1f5d2d9de70bd9a934f557dc95a406?d=identicon&s=25 Daniel ----- (liquid)
on 2006-06-01 03:03
(Received via mailing list)
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
This topic is locked and can not be replied to.