【问题标题】:creating an alias_attribute for a paperclip image in Rails在 Rails 中为回形针图像创建 alias_attribute
【发布时间】:2015-11-17 11:38:37
【问题描述】:

我目前正在构建一个模型为Post 的应用程序。我正在使用paperclip gem 上传图片,一切顺利。

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

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

image = Post.first.headerimage(:banner)

别名

但是,在我的应用程序中,它必须具有图像属性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)

但这不起作用。

【问题讨论】:

    标签: ruby-on-rails paperclip


    【解决方案1】:

    你可以试试这个——基本上是用参数调用原来的,因为别名不会带参数,但我们知道要传递的固定参数:

    alias :image, :headerimage
    
    def headerimage(name=nil)
      headerimage(name || :thumb)
    end
    

    【讨论】:

    • 谢谢!不知道我能做到这一点我觉得很傻:)
    • nw,老实说,你的问题很有用
    • 很好,这正是你需要的。
    • 所以,alias 需要实际的方法,而不是字符串或符号,并且不允许在它们之间使用逗号。另外,headerimage 方法会不会一直循环,直到达到堆栈深度限制并且您会崩溃?这到底是怎么工作的?
    猜你喜欢
    • 2018-08-25
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多