21

I try to follow http://api.rubyonrails.org/classes/ActiveModel/Validator.html , but where should I put the

 class MyValidator < ActiveModel::Validator
    def validate(record)
      if some_complex_logic
        record.errors[:base] = "This record is invalid"
      end
    end

    private
      def some_complex_logic
        # ...
      end
  end
JW8
  • 1,496
  • 5
  • 21
  • 36
wizztjh
  • 6,979
  • 6
  • 58
  • 92

3 Answers3

25

This guy puts them under app/validators/, which I've done as well, ever since I saw that blog post.

fresskoma
  • 25,481
  • 10
  • 85
  • 128
  • Any chance anyone knows how to display this folder in "Project" structure in Netbeans? I'm currently only able to access this folder through "Files", but i hate the tree hierarchy. – user1226868 Oct 17 '12 at 13:23
2

Add this class in your lib directory and require it in your model and include it inside.

shingara
  • 46,608
  • 11
  • 99
  • 105
1

Alternatively, you can also add it to the models directory of your app. Also, as mentioned by shingara, you need to add,

include ActiveModel::Validations
validates_with MyValidator 

to the model file of the record class.

sameer
  • 91
  • 5