Paperclip 是 Rails 的一個處理 attachment 的插件,相對於以往的 FileColumn 在靈活性和效率上更勝一籌,而且代碼也比較好看。這個視頻 簡單的介紹了 Paperclip 的使用方法。
默認的設置,URL 的佔位符中與模型本身相關的只有 id,但是一些情況下,你可能會更希望以其他形式來組織你的附件目錄 - 比如以 SKU 來代替數據庫記錄的 id。這裏我們暫不討論這種做法的好壞,雙方面的,好處是目錄結構更具有維護性,壞處是萬一以後升級數據庫,SKU 加個前綴什麼的…
Here we go!
使用 paperclip 需要在 model 中調用 has_attached_file 方法,檢查文檔,有一些簡單的使用樣例,但是沒有我們需要的。通過方法描述我們知道這個方法建立了一個 Paperclip::Attachment 對象,我們繼續看文檔。對象的方法很少,首先思考:應爲我們需要配置的是 attachment 的 url 規則,那麼應當是對應整個類而不是單個實力,因此我們只關注 Peperclip::Attachment 的類方法,只有兩個。default_options 沒有描述,而且展開代碼發現並不是我們需要的。
# Paperclip::Attchment.interpolation
A hash of procs that are run during the interpolation of a path or
url. A variable of the format :name will be replaced with the return
value of the proc named “:name”. Each lambda takes the attachment and
the current style as arguments. This hash can be added to with your own
proc if necessary.
這正是我們需要的,接下來的擴展就非常方便了:
# app/models/product.rb
class Product < ActiveRecord::Base
has_attached_file :photo,
:style => { :thumb => '64x64>' },
:url => '/images/products/:to_param.:extension'
def to_param
return self.sku
end
end
# config/initializers/paperclip.rb
Paperclip::Attachment.interpolations.merge!(
:to_param => lambda { |attachment, style| attachment.instance.to_param }
)
在這裏不直接使用 :sku 作爲佔位符而使用 :to_param 是爲了在其他模型中更加的靈活。