我正在模型中进行一些验证,并对如何针对3种不同的特定长度进行验证感到好奇?我想专门针对UPC验证10、12或13。我在文档中看到了具体如何做的事情。
class Product < ApplicationRecord
validates :name, presence: true, length: { maximum: 1024 }, uniqueness: true
validates :upc, presence: true, numericality: { only_integer: true }, length: { is: 10 }, uniqueness: true
has_many :product_properties
has_many :properties, through: :product_properties
end
感谢您能给我任何帮助。
答案 0 :(得分:2)
您必须编写一个自定义方法
validate :check_for_length
def check_for_length
errors.add(:upc, :wrong_length) unless [10,12,13].include?(upc.length)
end
现在输入您的en.yml
en:
activerecord:
errors:
models:
product:
attributes:
upc:
wrong_length: "your_message"