Jus*_*yes 0 ruby-on-rails custom-validators
每次我调用 validates_with NumberValidator 时。我收到未初始化的常量错误。我在“app”目录下创建了一个名为验证器的目录。这是我到目前为止。
这是我的模型
class Worker < ActiveRecord::Base
include ActiveModel::Validations
validates_with NumberValidator
end
Run Code Online (Sandbox Code Playgroud)
这是我的验证器文件
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
Run Code Online (Sandbox Code Playgroud)
我已经重新启动了我的服务器,但我不确定我做错了什么
app/假设您遵循预期的结构,Rails 将自动加载任何内容。Rails 这样做的方法是使用常量自动加载,它将常量映射MyValidator到文件名,例如my_validator.rb在自动加载路径中的目录下。
为了让Rails加载你NumberValidator,你应该命名该文件number_validator.rb,并把它放在一个文件夹中的自动加载路径,如app/validators/number_validator.rb。如果您在下面添加了一个目录,您将需要重新启动服务器,app因为这些目录是在启动时初始化的(spring stop如果您使用的是 spring,请务必运行,以便它也重新启动!)。
笔记:
app到你的应用程序配置,这样你就可以删除config.autoload_paths线。ActiveRecord::Base已经包含ActiveModel::Validations,所以你也可以include从你的Worker类中删除它。有关此过程如何工作的更多信息,请查看Rails 指南中的自动加载和重新加载常量页面。
| 归档时间: |
|
| 查看次数: |
1563 次 |
| 最近记录: |