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異常。