Every time I call validates_with NumberValidator. I get an uninitialized constant error. I have created a directory called validators under the "app" directory. This is what I have so far.
This is my model
class Worker < ActiveRecord::Base
include ActiveModel::Validations
validates_with NumberValidator
end
This is my validator file
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
I have restarted my server and I'm just not sure what I am doing wrong
Rails will automatically load anything under
app/
assuming you follow the expected structure. The way Rails does this is with Constant Autoloading, which maps a constant, such asMyValidator
to a file name, such asmy_validator.rb
under a directory in the autoload paths.In order for Rails to load your
NumberValidator
, you should name the filenumber_validator.rb
and put it in a folder in the autoload path, such asapp/validators/number_validator.rb
. You will need to restart the server if you have added a directory underapp
because these are initialized at boot time (be sure to runspring stop
if you are using spring so it restarts too!).Notes:
app
to your app config, so you can remove theconfig.autoload_paths
line.ActiveRecord::Base
already includesActiveModel::Validations
, so you can also remove thatinclude
from yourWorker
class.For more information on how this process works, check out the Autoloading and Reloading Constants page in the Rails Guides.