Custom validator not loading in Ruby on Rails

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

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 

A validator is a file located in an application / validator and containing 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 putting it in the lib folder, but this also gives this error:

 Routing Error uninitialized constant Issue::YesNoValidator 

Accidentally F5'ing sometimes I get this error:

 NoMethodError in IssuesController#new undefined method `key?' for nil:NilClass 

So it looks like the class file is not loaded, so I tried to add both lib and the app / validators folder to autoload_paths in application.rb. But that doesn't work either.

Has anyone experienced this before?

+4
source share
2 answers

In your application.rb application, add the application / validator path to the automatic download path

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

or manually request verification in the Issue.rb file.

+4
source

If you have not already done so, try restarting the Rails server so that your changes to application.rb can be taken into account.

+2
source

All Articles