2

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.

Baze_
  • 130
  • 8
  • Possible duplicated http://stackoverflow.com/questions/2328984/rails-extending-activerecordbase – Luís Ramalho Apr 04 '13 at 14:38
  • Would you give an example of why you need to clean inputs? Input is, by default, treated as unsafe when you display to users (you have to call "raw" to display any html tags). – Jesse Wolgamott Apr 04 '13 at 16:35
  • On display, inputs are cleaned, but I want to clean it before saving in database – Baze_ Apr 04 '13 at 16:40

2 Answers2

1

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
tbem
  • 595
  • 4
  • 14
  • Seems exactly what I look for, but define things as you say return the error : `uninitialized constant SuperModel` any idea ? – Baze_ Apr 04 '13 at 16:39
  • 1
    Okkkayyy ! I'm dumb. This is PER-FECT ! It's doing exactly what I wanted. Thank you very much, you're magic ! – Baze_ Apr 04 '13 at 16:43
0

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

Community
  • 1
  • 1
tbem
  • 595
  • 4
  • 14
  • Thanks for help. Seems interesting but even in this case I have to declare `validates_with` in all models. I thought that I can make an automated validation for all model without declare in each one. – Baze_ Apr 04 '13 at 15:26