为什么我的App / Validators出错?

时间:2015-02-17 17:01:50

标签: ruby-on-rails ruby ruby-on-rails-3 validation customvalidator

我一直在尝试验证名字不包含除字母,数字,连字符或下划线之外的任何内容。

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

validates :first_namename, :firstname_convention => true

哪个转到FirstNameConvention类:

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

但这仍然无效。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

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

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

就是这样