简体   繁体   中英

ActiveModel custom EachValidator not found

My EachValidator cannot work on Rails 4.1.5.

My Product model:

class Product < ActiveRecord::Base
  has_many :tags

  validates :tags, tags_size: {minimum: 1, maximum: 10}
end

My Validator, I put it in app/validators/tags_size_validator.rb

class TagsSizeValidator < ActiveModel::Validator

  def validate_each(record, attribute, value)
    if value.size < options[:maximum]
      record.errors[attribute] << (options[:message] || "must have at most #{options[:maximum]} tags.")
    end

    if value.size > options[:minimum]
      record.errors[attribute] << (options[:message] || "must have at lease #{options[:minimum]} tags.")
    end
  end
end

end

I have made it autoload in application.rb

config.autoload_paths += %W["#{Rails.root}/app/validators/"]

When I put the validator at the same file as the Product model, it worked perfectly. But in separated file it failed. Are there any steps I have missed? Please advise. Thanks.

Try inheriting from ActiveModel::EachValidator rather than ActiveModel::Validator :

class TagsSizeValidator < ActiveModel::EachValidator
...

Also you shouldn't have to add it to your autoload_paths in Rails 4.1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM