vendredi 4 septembre 2015

How to use interpolation to make upload path dynamic paperclip ruby on rails?

I have following model and controller setup on my app

attr_accessible :upload
  has_attached_file :upload,
    :url => "/files/docs/:basename.:extension"
    :path => "/files/docs/:basename.:extension"

  include Rails.application.routes.url_helpers

  def to_jq_upload
    {
      "name" => read_attribute(:upload_file_name),
      "size" => read_attribute(:upload_file_size),
      "url" => upload.url(:original),
      "delete_url" => upload_path(self),
      "delete_type" => "DELETE" 
    }
  end

and controller

def create
    @upload = Upload.new(params[:upload])

    respond_to do |format|
      if @upload.save
        format.html {
          render :json => [@upload.to_jq_upload].to_json,
          :content_type => 'text/html',
          :layout => false
        }
        format.json { render json: {files: [@upload.to_jq_upload],param:params}, status: :created, location: @upload }
      else
        format.html { render action: "new" }
        format.json { render json: @upload.errors, status: :unprocessable_entity }
      end
    end
  end

now I want to upload my files to different folders like docs, images etc, so I need to make /docs dynamic in path

In file upload form I have added a hidden field with name folder and set value "docs" but when I use it in model to make path dynamic it gives me error following is the code I tried

has_attached_file :upload,
    :url => "/files/#{params[:folder]}/:basename.:extension"
    :path => "/files/#{params[:folder]}/:basename.:extension"

when I check I can see folder name in params but I am not able to use it in model.

I also tried interpolation

Paperclip.interpolates :folder do |attachment, style|
    attachment.instance.params[:folder]
  end

but no result.

Is there any way to make path dynamic using params ?

Aucun commentaire:

Enregistrer un commentaire