2

I'm trying to write a custom validator that will check for the number of words entered into a text field.

I was trying to follow the example in railscasts episode 211 - http://railscasts.com/episodes/211-validations-in-rails-3

So I made a file /lib/word_limit_validator.rb and copied in the same code from the tutorial. I know that this code doesn't count the number of words, I am just trying to use it because I know how it is supposed to behave.

class WordLimitValidator < ActiveModel::EachValidator  
  def validate_each(object, attribute, value)  
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i  
      object.errors[attribute] << (options[:message] || "is not formatted properly")  
    end  
  end  
end

Here's the line I used in my validation:

  validates :body, :presence => true,
                   :word_limit => true

When I tried to load the form I got the following error:

Unknown validator: 'word_limit'

How do I get rails to recognize my validator?

System spec: Mac OS 10.6.7 Rails 3.0.4 ruby 1.9.2p136

2 Answers 2

10

You could also create an app/validators directory in your rails project and put your custom validators there. This way they will automatically be loaded.

Sign up to request clarification or add additional context in comments.

1 Comment

It works but... when I change something in app/validators/*.rb Rails (or Spork) doesnt reload code. A quick workaround is to add another watch line to Guardfile.
1

Files in lib/ aren't autoloaded anymore in Rails. So, you have a few options.

  • You can add lib to your autoload paths in your application.rb:
    config.autoload_paths += %W( #{config.root}/lib )
  • You can include by adding file with something like this to config/initializers: require File.join( Rails.root, 'lib', 'word_limit_validator')
  • If you only need it one place, you can just put it in the same file as your model.

1 Comment

Yeah, I should've said -- the second option is IMO the best option. Not sure what the Rails 3 'best practice' is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.