我在我的应用上设置了以下型号和控制器
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
和控制器
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
现在我想将我的文件上传到不同的文件夹,如文档,图片等,所以我需要在路径中创建/ docs动态
在文件上传表单中,我添加了一个带有名称文件夹和设置值“docs”的隐藏字段,但是当我在模型中使用它来使路径动态时,它给出了错误以下是我尝试过的代码
has_attached_file :upload,
:url => "/files/#{params[:folder]}/:basename.:extension"
:path => "/files/#{params[:folder]}/:basename.:extension"
当我检查时我可以在参数中看到文件夹名称,但我无法在模型中使用它。
我也试过插值
Paperclip.interpolates :folder do |attachment, style|
attachment.instance.params[:folder]
end
但没有结果。
有没有办法让params使路径动态化?
答案 0 :(得分:1)
您需要进行一些更改才能获得所需的结果。
folder
添加到模型中,以便在保存表单时保存该字段。更新您的模型,并移除path
的{{1}}和url
选项:
has_attached_file
更新您的环境(例如has_attached_file: :upload
)回形针配置以使用插值和动态路径:
config/environments/development.rb
实施插值以在# Paperclip defaults
config.paperclip_defaults = {
# other paperclip options for storage type e.g. file or S3
# important part
path: '/files/:dynamic_path'
}
初始值设定项
config/initializers/paperclip.rb