0

I am going to limit the user can upload only one image, if user go to upload more than one it will show error like this ‘You can upload max 1 images'

I am using paperclip gem for upload image it work fine and I add user_id to profile model using migration, Now I am going to limit image upload but getting error

I refer this stackover post Rails:Limiting how many files a user can upload

models/profile.rb

class Profile < ApplicationRecord

belongs_to :user
has_attached_file :profile_image, styles: { medium: "300x300>", thumb: "100x100>" },default_url: "/images/:style/missing.png"
validate :validate_profile_images, :on => :create 
private
def validate_profile_images
  return if profile_images.count <= 1
  errors.add(:profile_images, 'You can upload max 1 images')
end

end

models/user.rb

class User < ApplicationRecord

has_many :profiles

end

controllers/profiles_controller.rb

class ProfilesController < ApplicationController

before_action :find_profile, only: [:show, :edit, :update, :destroy]

def new

@profile = current_user.profiles.build

end

def create
  @profile = current_user.profiles.build(profile_params)
  if @profile.save
  redirect_to profile_path(@profile.user.id)
  else
  render "new"
  end
end 
end

private

def profile_params
    
  params.require(:profile).permit(:profile_image,:date_of_birth)
    
end

def find_profile

  @profiles = Profile.where(params[:id])

end

views/profiles/_form.html.erb

<%=simple_form_for @profile, url: profiles_path, html: { multipart: true } do |f| %>

<%= f.label :profile_image,'Your Photo'%></br>
 <%= f.file_field :profile_image%></br>

<%=f.label :date_of_birth,'Birth Year'%></br>
<%= f.date_field :date_of_birth,:order => [:day, :month, :year]%></br>


<%= f.submit"Upload Image",:title => "Your photo”%>

<%end%>
code_aks
  • 1,972
  • 1
  • 12
  • 28
adarsh
  • 306
  • 5
  • 16

1 Answers1

0

We need a little bit more explanation about what do you want to do.

But with what you said and as i understood:

You're using a ("has_one_attached") not (has_many_attached)

  • The "has_one" should limit the relation to only have 1 record.

And if the file_field is not :multiple, the user shouldn't be able to do upload more than one file.