Mike McCallen Mike McCallen - 10 months ago 101
Ruby Question

Paperclip dimension validation error in Rails 4

I want in my app user to be able to upload files with

at least
height: 550px

I created in app/models/dimensions_validator.rb file
and the code

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

record.errors[attribute] << "Width must be at least #{width}px" if dimensions.width < width
record.errors[attribute] << "Height must be at least #{height}px" if dimensions.height < height

and in my app/models/gig.rb model

validates :image, :dimensions => { :width => 800, :height => 550 }

Question: When i click on the submit button,without actually selecting any picture,it throughs an error saying
undefined method
"path" for nil:NilClass

and it marks in red color the line 4 which is
dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path)

Maybe i need a code,to check if the image is present,something like
if image.present?
but where would i include that? i already use in the gig model
validates_attachment_presence :image

This is the error

And this is my GigsController#update

def update
if @gig.update(gig_params)
redirect_to @gig, notice: "Gig was successfully updated"
render "edit"

Answer Source

Try this.

validates :image, :unless => "image.queued_for_write[:original].blank?", dimensions: { width: 800, height: 550 }