[英]Paperclip dynamic styles based on polymorphic parent class doesn't work (Rails 4.2.5, Paperclip 4.3.1)
[英]Rails Paperclip polymorphic styles
我正在使用paperclip為使用accepts_nested_attributes_for的多個模型的附件。 有沒有辦法為每個模型指定特定的回形針樣式選項?
是。 我在站點上使用單表繼承(STI)來通過Asset模型處理音頻,視頻和圖像。
# models/Asset.rb
class Asset < ActiveRecord::Base
# Asset has to exist as a model in order to provide inheritance
# It can't just be a table in the db like in HABTM.
end
# models/Audio.rb
class Audio < Asset # !note inheritance from Asset rather than AR!
# I only ever need the original file
has_attached_file :file
end
# models/Video.rb
class Video < Asset
has_attached_file :file,
:styles => {
:thumbnail => '180x180',
:ipod => ['320x480', :mp4]
},
:processors => "video_thumbnail"
end
# models/Image.rb
class Image < Asset
has_attached_file :file,
:styles => {
:medium => "300x300>",
:small => "150x150>",
:thumb => "40x40>",
:bigthumb => "60x60>"
}
end
它們都進入Rails as :file
,但控制器(A / V / I)知道保存到正確的模型。 請記住,任何媒體形式的所有屬性都需要包含在Asset
:如果視頻不需要字幕而圖像不需要,那么Video
的標題屬性將為零。 它不會抱怨。
如果連接到STI模型,協會也將正常工作。 User has_many :videos
運行方式與您現在使用的相同,只是確保您不要嘗試直接保存到資產。
# controllers/images_controller.rb
def create
# params[:image][:file] ~= Image has_attached_file :file
@upload = current_user.images.build(params[:image])
# ...
end
最后,由於您確實擁有資產模型,因此您仍然可以直接從中讀取,例如,如果您需要20個最近資產的列表。 此外,此示例不限於分離媒體類型,它也可以用於不同類型的同一事物:頭像<資產,圖庫<資產等。
一個更好的方法可以是(如果使用處理圖像):
class Image < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
has_attached_file :attachment, styles: lambda {
|attachment| {
thumb: (
attachment.instance.imageable_type.eql?("Product") ? ["300>", 'jpg'] : ["200>", 'jpg']
),
medium: (
["500>", 'jpg']
)
}
}
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.