【发布时间】:2015-02-17 17:01:49
【问题描述】:
我一直在尝试验证名字是否包含字母、数字、连字符或下划线。
在我的 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
但这仍然不起作用。
我做错了什么?
【问题讨论】:
-
app/validators 可能不在通常的 Rails 路径中。尝试将您的文件夹放入 lib/validators 中,看看是否适合您
-
那么把验证器文件夹放在那里?
-
是的。这是我的建议
-
我应该在哪里创建 lib 文件夹?在默认站点目录中?
-
lib 文件夹应该已经存在(在你的应用程序的根目录中)!如果找不到类等,Rails 将查看此文件夹。
标签: ruby-on-rails ruby ruby-on-rails-3 validation customvalidator