Validation? Cool... How about before_save formatting

Hello,

I am trying to define a before_save method in an object. I would like to call a function like sanitize or simple_format. These are view functions. Is there any way, short of writing my own functions, to sanitize a user's text input BEFORE it is saved to the database rather than after?

Thanks!

Mindtonic wrote:

Hello,

I am trying to define a before_save method in an object. I would like to call a function like sanitize or simple_format. These are view functions. Is there any way, short of writing my own functions, to sanitize a user's text input BEFORE it is saved to the database rather than after?

Thanks!

The ActiveRecord Callbacks for before_save and before_create might help: http://railsmanual.com/module/ActiveRecord::Callbacks

Cheers, Mohit. 8/14/2007 | 10:49 PM.

Sweet...

What I am looking for are pre-existing methods that I can call from within before_save that will serve the same function as sanitize or simple_format.

http://snipplr.com/view/2505/use-helpers-in-controllers-or-models/

Thanks! That is exactly what I was looking for.

Singleton no less, very interesting!

I am of the philosophy that you should clean and format before you store in the database and this is an excellent way to do it.

that snippet is actually a little more verbose than necessary but with the benefit of namespacing the methods into help.xxx()

if you wanted you could simply require the ActionView helper module in your application.rb:   include ActionView::Helpers::TextHelper

and that's it... just call "sanitize('whatever')" in your controllers directly

IMHO it is a gigantic deficiency of Rails that there is not an out-of-the-box way to do this. h() is good but why filter output in 100 places when you can filter input once?

well, you can... exactly as described above or write your own methods. IMHO it's not rails' place to do this automatically - you might want to have those special characters in the db.