为什么我的 App/Validators 会出错?

Why do I get errors with my App/Validators?

我一直在尝试验证名字是否只包含字母、数字、连字符或下划线。

在我的 users.rb 模型中,我使用此代码:

validates :first_namename, :firstname_convention => true

参加 FirstNameConvention class:

class FirstnameConventionValidator < ActiveModel::EachValidator
  def validate_each(record, field, value)
    unless value.blank?
      record.errors[field] << "is not alphanumeric (letters, numbers,   underscores or periods)" unless value =~ /^[[:alnum:]._-]+$/
      record.errors[field] << "should start with a letter" unless value[0] =~ /[A-Za-z]/
      record.errors[field] << "contains illegal characters" unless    value.ascii_only?
    end
  end
end

并且该文件存储在 app/validators - 我必须创建的文件夹中。

我收到这个错误:

ArgumentError in UsersController#index
Unknown validator: 'FirstnameConventionValidator'

我试过放置:

config.autoload_paths += %W["#{config.root}/app/validators"]

在config/application.rb:

 require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ThorCinema
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.

# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'

# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de

# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true    
config.autoload_paths << Rails.root.join('app', 'validators')
end

end

但这还是不行。

我做错了什么?

app/validators 是存储验证器的好地方,您需要做的就是告诉 Rails 这个文件夹的存在。将此行添加到 config/application.rb 中的自动加载路径(YourAppName::Application 部分):

config.autoload_paths << Rails.root.join('app', 'validators')

就是这样