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?
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.
If you haven't already, try restarting Rails server so that your changes in application.rb may be taken into account.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With