1

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!

Dl33ter
  • 85
  • 10

1 Answers1

3

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
dtt101
  • 2,151
  • 25
  • 21
  • Really nice! I only had to replace validates_on_create by -> validate :images_limit, :on => :create. I still have a problem, when the error message is displaying, I have many fields as images I tried to send. If I attach 15 photos, I will have 15 files filds + the first (so 16). In my controller I add: @post.photos.build to show the field of my form => <%= f.fields_for :images do |images| %> <%= image.file_field :image ... and so on. Do you have any idea for that? Anyway, your code is working to validate! Thank you! – Dl33ter Aug 21 '13 at 17:00
  • I forgot, I had to change errors.add("message") bu errors.add(:images, "message). Just in case if someone else need it to. – Dl33ter Aug 21 '13 at 17:30
  • Glad it helped - mark the answer if you think it would be useful to someone else :) – dtt101 Aug 21 '13 at 21:39