[英]CarrierWave use one uploader two times in single model
我有一個名為User
的模型。 它具有兩個字段: small_logo
和big_logo
。 這些實際上是不同的圖片,而不僅僅是一張調整大小的圖片。
class User < ActiveRecord::Base
...
mount_uploader :big_logo, UserLogoUploader
mount_uploader :small_logo, UserLogoUploader
...
end
我使用UserLogoUploader
上傳此圖片。
而且我遇到了一個錯誤-只要模型名稱相同,上傳的文件就會具有相同的路徑,因此,如果我嘗試上傳兩個具有相同名稱的文件-第二個將覆蓋第一個。
顯而易見的解決方案是為這些字段使用不同的上傳器。 但是我不想創建另一個上載程序來解決此錯誤-我可以做些什么來修改文件名,例如,使用有意義的東西(例如提交此文件的表單域的名稱或訪問該文件的模型域的名稱)正在處理中。
經過一番搜尋后找到了我自己問題的答案
在上載器中有一個mounted_as
屬性,與docs相對應,它確實滿足我的需求:
If a model is given as the first parameter, it will stored in the uploader, and
available throught +#model+. Likewise, mounted_as stores the name of the column
where this instance of the uploader is mounted. These values can then be used inside
your uploader.
因此,整個解決方案如下所示:
def UserLogoUploader < CarrierWave::Uploader::Base
...
def store_dir
File.join [
Settings.carrierwave.store_dir_prefix,
model.class.to_s.underscore,
mounted_as.to_s,
model.id.to_s
].select(&:present?)
end
...
end
此代碼為不同的模型字段創建不同的子文件夾,這有助於防止名稱重復和文件覆蓋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.