0 前言
1 更改paperclip默认的上传位置
class Story < ActiveRecord::Base
has_attached_file :cover,
:styles=>{:small=>"32x32"},
:path => ":rails_root/paperclip/:class/:attachment/:id/:style/:filename",
:url => "/paperclip/:class/:attachment/:id/:style/:filename"
end
要同时修改path和url,url是相对于rails工程而言,被rails app用来获取图片渲染页面;而path是相对于rails app服务器而言,在整个宿主文件系统中的路径。必须同时修改path和url。
2 添加controller
get "/paperclip/:class/:attachment/:id/:style/:filename",to:"assets#show"
添加assets_controller.rb文件:
class AssetsController < ApplicationController
def show
cls=params[:class].singularize.capitalize.constantize
asset=cls.find params[:id]
send_file asset.send(params[:attachment].singularize).path(params[:style])
end
end
在提交的参数中params[:class]是复数形式,而通常类定义都是单数如Story,params[:attachment]是也复数形式而类定义中cover为单数,所以都要将他们变成单数,如果类中定义的attachment是复数形式,那么这里attachment就不必转换为单数,否则会引发NoMethod异常。