包含验证器时未初始化的常量

时间:2017-11-08 11:49:15

标签: ruby-on-rails ruby validation

我的Rails应用中有以下文件/app/validators/hex_color.rb

module Validators
  class HexColorValidator < ActiveModel::EachValidator

    def validate_each(record, attribute, value)
      unless value =~ /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i
        record.errors[attribute] << (options[:message] || 'must be a valid CSS hex color code')
      end
    end

  end
end

然后在我的模型中:/app/models/brand_theme.rb我有:

class BrandTheme < ApplicationRecord

  include Validators

  validates :brand_1, presence: true, hex_color: true

end

但我收到错误:

uninitialized constant BrandTheme::Validators

为什么不包含验证器?我也尝试过重置服务器,但同样的问题出现了。

1 个答案:

答案 0 :(得分:1)

您的课程没有加载,因为您没有遵循rails惯例。您不应该将它放到Validations模块中。我会使用模块HexColor ...而不是类。

所以这是解决方案......文件/app/validators/hex_color_validator.rb

module HexColorValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i
      record.errors[attribute] << (options[:message] || 'must be a valid CSS hex color code')
    end
  end
end

class BrandTheme < ApplicationRecord
  include HexColorValidator

  validates :brand_1, presence: true, hex_color: true
end

然后它将被自动加载。如果您想要几个模块,那么请将模块作为app/validators的子文件夹或仅包含几个单独的模块