【问题标题】:Rails Carrierwave acessing parent model from within a versionRails Carrierwave 从版本中访问父模型
【发布时间】:2013-08-02 14:40:17
【问题描述】:

我正在尝试在我的 carrierwave 上传器上创建一个版本,以检查它的父模型是否有一些关于如何调整图像大小和裁剪图像的数据,如果没有,则执行默认调整大小来填充。我一直在尝试引用此处演示的模型:https://github.com/carrierwaveuploader/carrierwave

如果我像这样运行版本代码:

version :title do
      if model.dimensions_hash["title"]
            process :image_crop => [model.dimensions_hash["title"], 960, 384]
      else
            process :resize_to_fill => [960, 384]
      end
  end

我收到此错误:

NameError: undefined local variable or method `model' for #<Class:0x007f9eae7cfed0>
    from /Users/RyanKing/Sites/test/app/uploaders/page_image_uploader.rb:45:in `block in <class:PageImageUploader>'

第 45 行是 process :image_crop =&gt; [model.dimensions_hash["title"], 960, 384


如果 if 语句返回 true,为什么第 45 行返回错误?我是否错误地引用了模型?

我在这里发现了一个类似的问题,但无法适应我的情况。 Passing a parameter to the uploader / accessing a model's attribute from within the uploader / letting the user pick the thumbnail size

【问题讨论】:

  • 模型变量指向上传器附加到的实例对象。你明白吗?
  • 是的,所以它应该指向带有mount_uploader :image, PageImageUploader 的模型,对吗?为什么model 是未定义的?
  • @RyanKing 错误,即因为模型是您的上传者的实例变量/对象,但条件是Uploader 上下文中的框架@ 即Class.new([Your Uploader]).model =&gt; hence undefined`,因为它类似于这个 Class.new([Your Uploader]).new(mount_as,mount_something).model`检查here

标签: ruby-on-rails ruby carrierwave


【解决方案1】:

你是对的 model 方法将不可用,因为 version 是一个

类方法,而model是上传者的实例方法

但是有办法得到它们

如果您检查我在邮件中附加的link,则块内定义的所有内容都是class_eval,因此考虑到这一点,您可以像这样修改您的代码

version :title do
  process :image_crop => [960, 384],:if => :has_title?
  process :resize_to_fill => [960, 384] ,:if => :has_not_title?

  def has_title?
     model.dimensions_hash["title"].present?
  end

  def has_not_title?
    not(has_title?)
  end
end

希望有帮助

【讨论】:

  • 我试图做这样的事情但失败了:process resize_to_limit: [2048, 2048] , if model.attachmentable_type = "Page"。看来model 无法通过这种方式访问​​。我得到undefined local variable or method model' for AttachmentUploader:Class`
  • @W.M.我正面临这个问题,您找到解决方案了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
相关资源
最近更新 更多