CalebHC
CalebHC

Reputation: 5042

Dynamic Attachment Size for Paperclip (Rails)

Is there anyway to have the validates_attachment_size except a dynamic file size limit? Here's an example:

class Document < ActiveRecord::Base
   belongs_to :folder
   has_attached_file :document
   validates_attachment_size :document, :less_than => get_current_file_size_limit

   private

   def get_current_file_size_limit
     10.megabytes # This will dynamically change
   end
end

I've tried this but I keep getting an error saying "unknown method". Lambdas and Procs don't work either. Has anyone ever tried this? Thanks

Upvotes: 3

Views: 2776

Answers (3)

shedd
shedd

Reputation: 4218

There is a built-in Paperclip validation now:

validates_attachment_size :mp3, :less_than => 10.megabytes

Change mp3 to whatever your paperclipped file's name is.

See this post for more helpful Paperclip tips: http://thewebfellas.com/blog/2008/11/2/goodbye-attachment_fu-hello-paperclip

Upvotes: 0

Tatjana N.
Tatjana N.

Reputation: 6225

Paperclip doesn't allow to pass function as size limit parameter. So you probably need to write custom validation:

  validate :validate_image_size

  def validate_image_size
    if document.file? && document.size > get_current_file_size_limit
      errors.add_to_base(" ... Your error message")
    end
  end

Upvotes: 6

Tony Fontenot
Tony Fontenot

Reputation: 5101

Long shot...

validates_attachment_size :document, :less_than => :get_current_file_size_limit

Usually when passing a function you have to pass the symbol and not the actual function.

Upvotes: 2

Related Questions