【问题标题】:Why do I get errors with my App/Validators?为什么我的应用程序/验证器会出错?
【发布时间】: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


【解决方案1】:

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

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

就是这样

【讨论】:

  • 我已经更新了问题以显示我把它放在哪里,但它仍然出现同样的错误。是因为我在 app 中创建了验证器文件夹,而不是由 rails 生成它吗?
  • @benjs.1 确保您重新启动了服务器/控制台。不,不需要使用生成器。您可以根据需要扩展您的应用程序。
猜你喜欢
  • 1970-01-01
  • 2013-11-08
  • 2021-11-08
  • 2017-10-05
  • 2021-09-24
  • 2020-07-29
  • 1970-01-01
  • 2019-04-27
  • 2021-08-11
相关资源
最近更新 更多