6

这是我的图片模型,其中我已经实现了一个方法,用于验证附件的尺寸:回形针图片尺寸自定义的验证

class Image < ActiveRecord::Base 
    attr_accessible :file 

    belongs_to :imageable, polymorphic: true 

    has_attached_file :file, 
        styles: { thumb: '220x175#', thumb_big: '460x311#' } 

    validates_attachment :file, 
         presence: true, 
         size: { in: 0..600.kilobytes }, 
         content_type: { content_type: 'image/jpeg' } 

    validate :file_dimensions 

    private 

    def file_dimensions(width = 680, height = 540) 
    dimensions = Paperclip::Geometry.from_file(file.queued_for_write[:original].path) 
    unless dimensions.width == width && dimensions.height == height 
     errors.add :file, "Width must be #{width}px and height must be #{height}px" 
    end 
    end 
end 

这工作得很好,但由于该方法采用固定值,它是不可重复使用宽度&高度。我想将其转换为自定义验证器,因此我也可以在其他模型中使用它。我读过有关这个导游,我知道这会是这样的应用程序/模型/ dimensions_validator.rb:

class DimensionsValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
    dimensions = Paperclip::Geometry.from_file(record.queued_for_write[:original].path) 

    unless dimensions.width == 680 && dimensions.height == 540 
     record.errors[attribute] << "Width must be #{width}px and height must be #{height}px" 
    end 
    end 
end 

,但我知道我失去了一些东西的原因此代码不能正常工作。问题是我想在我的模型中调用这样的验证:

validates :attachment, dimensions: { width: 300, height: 200}

关于如何实施验证器的任何想法?

+1

我不确定,但我认为你可以通过选项属性访问你的宽度和高度。就像:'options [:width]'和'options [:height]' –

回答

16

把这个在app /验证/ dimensions_validator.rb:

class DimensionsValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
    # I'm not sure about this: 
    dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path) 
    # But this is what you need to know: 
    width = options[:width] 
    height = options[:height] 

    record.errors[attribute] << "Width must be #{width}px" unless dimensions.width == width 
    record.errors[attribute] << "Height must be #{height}px" unless dimensions.height == height 
    end 
end 

然后,在模型中:

validates :file, :dimensions => { :width => 300, :height => 300 } 
+0

我们不必添加只要你将文件放在models /中,然后按照Rails约定(dimensions_validator.rb)命名,就可以将验证器命名为load_path。我编辑了答案。谢谢! – Agis

+0

我已经更新了答案.. –

+0

太好了。我们如何才能在图片上传时进行检查?我试过一些东西,除非record.nil?和'除非value.nil?'但它不起作用。 – Agis