在rails控制器中获取Carrierwave上传的文件名

时间:2014-01-05 12:35:39

标签: ruby-on-rails file-upload carrierwave

我需要在我的控制器中获取文件名和上传文件,以便我可以为上传的文件设置默认标题(或名称),如果用户没有指定一个。我使用Carrierwave上传文件。

我的控制器创建操作如下所示:

  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

1 个答案:

答案 0 :(得分:14)

解决方案是从carrierwave文件中获取文件名,如下所示:

  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
相关问题