Search code examples
ruby-on-railstwitter-bootstraprails-activestorage

Rails:Limiting how many files a user can upload


Users can upload multiple pictures for their posts in my rails app using active storage, is it possible to limit exactly how many photos they can upload in the form?I want to limit it to 4 pictures per user.

<%= f.file_field :images, multiple: true, required: false  %>

Solution

  • You can write custom validation. Add the following code to the related model.

    validate :validate_images
    
    private
    def validate_images
      return if images.count <= 4
    
      errors.add(:images, 'You can upload max 4 images')
    end
    

    Also you can check the limit on the client side. The following code is from this answer

    $(function(){
      $("input[type='submit']").click(function(){
        var fileUpload = $("input[type='file']");
        if(parseInt(fileUpload.get(0).files.length) > 4) {
          alert('You can upload max 4 images');
        }
      });    
    });​