2

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  %>

1 Answer 1

3

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');
    }
  });    
});​
Sign up to request clarification or add additional context in comments.

3 Comments

i'm getting this error "undefined method `images?' for #<Post:0x00007fc18e433990> Did you mean? images images="
@sokoine can you share model class?
the class is Post , "NoMethodError in PostsController#update"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.