Frage

I have an app for which I want to sanitize user inputs before saving it in the database. I can easily add in all model a function clean and call it with before_validation :clean, but my function clean is generic.

I wanted to know if it exist a way to call this function for all model validations in the app and just declare once.

I have made some research but I haven't find the answer for me, and it bothers me, repeat the function and the before_validation in all my models it's not quite DRY.

Thank you in advance for your responses.

Cheers.

War es hilfreich?

Lösung

Ok! I think you may want to use a super model to make some inheritance, because injection in active record base can be dangerous for yourself, so if you have a super model that descends from ActiveRecord base with that validation and after that, you create other models that descend this one you'll have that validation to all of them without needing to wright the validation again.

class SuperModel < ActiveRecord::Base
 #This if for avoid single table inheritance 
 self.abstract_class = true
 #-------------------------------------------------------------------------------
 before_validation :clean

end
class Example < SuperModel
 #this will have the before_validation :clean
end

Andere Tipps

I think you want to extend Active record validations... Take a look at this: Adding custom validations to ActiveRecord module via extend?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top