簡體   English   中英

在Rails中為回形針圖像創建alias_attribute

[英]creating an alias_attribute for a paperclip image in Rails

我目前正在構建一個具有模型Post的應用程序。 我正在使用paperclip gem來上傳圖像,並且一切進展順利。

class Post < ActiveRecord::Base
    has_attached_file :headerimage, styles: {banner => "400x300#"}
end

如您在上面的類中所看到的,如果我要獲取Post對象,則可以在視圖中獲得帶有以下內容的橫幅圖像:

image = Post.first.headerimage(:banner)

別號

但是,在我的應用程序中,它必須具有圖像屬性image ,該image引用縮略圖。 所以,在我的模型課上,我寫了

class Post < ActiveRecord::Base
    has_attached_file :headerimage, styles: {banner => "400x300#"}
    alias_attribute :image, :headerimage
end

這使我可以通過調用以下命令獲取圖像:

image = Post.first.image

這就是我想要的-但是,它是從回形針獲取原始圖像的,所以等效於編寫以下內容:

image = Post.first.headerimage而不是image = Post.first.headerimage(:banner)

如何設置適當的alias_attribute來訪問回形針縮略圖? 我似乎在其他任何地方都找不到答案,而且我不確定回形針的實際工作方式。

我以為我在邏輯上可以做類似的事情

alias_attribute :image, :headerimage(:banner)

但這不起作用。

您可以嘗試一下-由於別名不會接受參數,因此基本上可以使用參數調用原始參數,但是我們知道要傳遞固定參數:

alias :image, :headerimage

def headerimage(name=nil)
  headerimage(name || :thumb)
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM