I need to get the file name of and uploaded file in my controller so that i could set a default title (or name) to the uploaded file if the user did not assign one. I use Carrierwave to upload ing files.
My controller create action looks like this:
def create
@photo = Photo.new(params[:photo])
@photo.user_id = current_user.id
respond_to do |format|
if @photo.save
format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
format.json { render action: 'show', status: :created, location: @photo }
else
format.html { render action: 'new' }
format.json { render json: @photo.errors, status: :unprocessable_entity }
end
end
end
The solution was to get the filename from the carrierwave file like this:
def create
@photo = Photo.new(params[:photo])
@photo.user_id = current_user.id
@photo.name = @photo.image.file.filename if @photo.name == ""
respond_to do |format|
if @photo.save
format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
format.json { render action: 'show', status: :created, location: @photo }
else
format.html { render action: 'new' }
format.json { render json: @photo.errors, status: :unprocessable_entity }
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With