Search code examples
ruby-on-railsruby-on-rails-3paperclippaperclip-validation

Rails - Paperclip - Multiupload - How to limit number of images?


I have a Rails 3.2 application using Paperclip to attach mutliple images in one fied.

So, I have a Post model and a Image model.

My question is: How to validate the number of image like the size validation of Paperclip?

Thanks!


Solution

  • S0 I am assuming that one Post has_many Images.

    You could try validating the number of images on save, something like the following (this code has not been tested!):

    class Post
      has_many :images
      validate_on_create :images_limit
    
      private
    
      def images_limit
        return if images.blank?
        errors.add("You have reached the image limit") if images.length > 10
      end
    end
    
    class Image
      belongs_to :post
      validates_associated :post
    end