wizztjh
wizztjh

Reputation: 7051

where to put ActiveModel::Validator?

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

Upvotes: 22

Views: 4789

Answers (3)

fresskoma
fresskoma

Reputation: 25791

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

Upvotes: 25

sameer
sameer

Reputation: 91

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.

Upvotes: 1

shingara
shingara

Reputation: 46914

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

Upvotes: 2

Related Questions