我有以下导轨/回形针验证器:
class ImageRatioValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
attr_name = "#{attribute}_width".to_sym
value = record.send(:read_attribute_for_validation, attribute)
valid_ratios = options[:ratio]
if !value.queued_for_write[:original].blank?
geo = Paperclip::Geometry.from_file value.queued_for_write[:original]
# first we need to validate the ratio
cur_ratio = nil
valid_ratios.each do |ratio, max_width|
parts = ratio.split ":"
next unless (geo.height * parts.first.to_f) == (geo.width * parts.last.to_f)
cur_ratio = ratio
end
# then we need to make sure the maximum width of the ratio is honoured
if cur_ratio
if not valid_ratios[cur_ratio].to_f >= geo.width
record.errors[attribute] << "The maximum width for ratio #{cur_ratio} is #{valid_ratios[cur_ratio]}. Given width was #{geo.width}!"
end
else
record.errors[attribute] << "Please make sure you upload a stall logo with a valid ratio (#{valid_ratios.keys.join(", ")})!"
end
end
end
end
验证器用于超类(超类不是抽象的,因此可以实例化)和子类。在子类中,我需要更改允许的比率:
超类:
class Superclass
validates_attachment :logo, :image_ratio => { :ratio => {"1:1" => "28", "4:1" => "50", "5:1" => "40"} }
end
子类:
class Subclass < Superclass
validates_attachment :logo, :image_ratio => { :ratio => {"1:1" => "40", "2:1" => "60"} }
end
验证器在超类中按预期工作,但似乎忽略了子类中给出的新比率。
我是否试图以非 Rails 方式使用验证器?在上述情况下,我应该如何使用验证器?