을 치수이 내가 첨부 파일의 크기를 확인하는 방법을 구현했습니다하는 내 이미지 모델은 다음과 같습니다종이 클립 이미지는 사용자 정의 유효성 검사기
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에서
잘 모르겠지만 options 속성을 통해 너비와 높이에 액세스 할 수 있다고 생각했습니다. like :'options [: width]'및'options [: height]' –