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}.

이 유효성 검사기를 구현하는 방법에 대한 아이디어가 있으십니까? 응용 프로그램/검증/dimensions_validator.rb에서

+1

잘 모르겠지만 options 속성을 통해 너비와 높이에 액세스 할 수 있다고 생각했습니다. like :'options [: width]'및'options [: height]' –

답변

16

넣고이 :

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 /에 놓고 레일 규칙 (dimensions_validator.rb)에 따라 이름을 지정하는 한 validator를 load_path에 추가합니다. 나는 대답을 편집했다. 감사! – Agis

+0

답변을 업데이트했습니다 .. –

+0

우수. 이미지가 업로드 된 경우에만 어떻게 점검을 수행 할 수 있습니까? 나는 record.nil이 아닌 한 무언가를 시도했다. 'value.nil이 아닌 이상?' 그러나 그것은 작동하지 않았다. – Agis

관련 문제