Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validator does not load in Ruby on Rails

I am trying to apply a custom validator to my model issue.rb:

class Issue < ActiveRecord::Base
  attr_accessible :description, :no_followers, :title
  validates_presence_of :title
  validates_uniqueness_of :title, message: "Title should be unique!"

  validates_length_of :description, minimum: 10, maximum: 50
  validates_numericality_of :no_followers, allow_blank: true

  validates_with YesNoValidator

end

The validator is a file located at app/validators and contains the following:

class YesNoValidator < ActiveModel::Validator
    def validate record
        if record.title.include? "yes" && record.description.include? "No"
            record.errors[:title] << "Title has the word yes and description has the word no"
        end 
    end
end

I also tried to put it inside the lib folder but that also gives this error:

Routing Error

uninitialized constant Issue::YesNoValidator

At random F5'ing I sometimes get this error:

NoMethodError in IssuesController#new

undefined method `key?' for nil:NilClass

So it seems like the file with the class is not loaded so I tried adding both the lib as well als the app/validators folder to the autoload_paths in application.rb. But this doesn't work either..

Has anyone experienced this before?

like image 779
Sjaak Rusma Avatar asked Apr 23 '13 15:04

Sjaak Rusma


2 Answers

In your application.rb, add the app/validators path to the auto load path

config.autoload_paths += [Rails.root.join('app', 'validators').to_s]

or manually require the validator in the Issue.rb file.

like image 146
manoj Avatar answered Nov 17 '22 09:11

manoj


If you haven't already, try restarting Rails server so that your changes in application.rb may be taken into account.

like image 3
André Avatar answered Nov 17 '22 09:11

André