在 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

正如您在上面的 class 中所看到的,如果我要获得一个 Post 对象,我可以在我的视图中获得带有以下内容的横幅图像:

image = Post.first.headerimage(:banner)

别名

但是,在我的应用程序中,它必须具有图像属性image来引用缩略图。所以,在我的模型 class 中,我写了

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