Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file name of Carrierwave upload in rails controller

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
like image 923
Ole Henrik Skogstrøm Avatar asked Jan 05 '14 12:01

Ole Henrik Skogstrøm


1 Answers

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
like image 191
Ole Henrik Skogstrøm Avatar answered Oct 19 '22 10:10

Ole Henrik Skogstrøm