问题描述
每次我调用 validates_with NumberValidator.我得到一个未初始化的常量错误.我在"app"目录下创建了一个名为验证器的目录.这是我目前所拥有的.
这是我的模特
class Worker < ActiveRecord::Base include ActiveModel::Validations validates_with NumberValidator end
这是我的验证器文件
class NumberValidator < ActiveModel::Validator def validate(record, attribute, value) puts record puts attribute puts value end end require File.expand_path('../boot', __FILE__) require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module ApplicationName 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 += %W["#{config.root}/app/validators/"] end end
我已经重新启动了我的服务器,但我不确定我做错了什么
推荐答案
假设您遵循预期的结构,Rails 将自动加载 app/ 下的任何内容.Rails 执行此操作的方式是使用常量自动加载,它将常量,例如 MyValidator 映射到文件名,例如自动加载路径中目录下的 my_validator.rb.
为了让 Rails 加载您的 NumberValidator,您应该将文件命名为 number_validator.rb 并将其放在自动加载路径中的文件夹中,例如 app/validators/number_validator.rb.如果您在 app 下添加了一个目录,则需要重新启动服务器,因为这些目录是在启动时初始化的(如果您使用的是 spring,请确保运行 spring stop,这样它也会重新启动!).
注意事项:
- 您确实不需要将 app 下的任何内容添加到您的应用配置中,因此您可以删除 config.autoload_paths 行.
- ActiveRecord::Base 已经包含 ActiveModel::Validations,因此您也可以从 Worker 类中删除该 include.
有关此过程如何工作的更多信息,请查看 自动加载和重新加载常量页面Rails 指南.
相关问答
Rails 3的自定义验证器应该存放在哪里?
Zend框架-我们应该把我们的自定义验证器放在哪里?
Rails - 在Application.rb中添加了4个自定义资产路径而无需重新启动
在Laravel 5中,我应该把自定义字体放在哪里?
在Rails项目中,自定义响应器应该放在哪里?
资产管道错误但config.assets.enabled = false in application.rb
自定义按钮字体的这行代码应该放在哪里?
我应该在哪里将onclickListener放在自定义ListView上?
我应该把onClickListener放在自定义列表视图的哪里?
在Laravel中把自定义/新的类文件放在哪里?