【问题标题】:Global error handler for specific case. Undefined method 'public_url'针对特定情况的全局错误处理程序。未定义的方法“public_url”
【发布时间】:2020-02-20 11:38:15
【问题描述】:

ruby '2.5.1'

rails '5.1.7'

我的项目是声音管理。所有上传的文件都在云存储中 - 声音/声音图像/专辑图像等。

但是云存储上的一些文件不存在。并查看以下代码:

.row
  - @sounds.each do |sound|
    .col-md-2
      .play{ "image-src": "#{sound.image.url(:small)}", style: "background: url(#{sound.image.url(:small)});" }

我收到以下错误:

ActionView::Template::Error (undefined method `public_url' for nil:NilClass)

项目中有很多这样的循环(@sounds.each),所以我不想每个都重写。

如何为这种情况编写错误处理程序?因此,在没有存储文件的情况下,会跳过声音。

也许有办法在application_controller.rb 或类似的地方编写代码?

我将gem 'carrierwave-google-storage' 用于图片,gem 'google-cloud-storage' 用于附件。

【问题讨论】:

  • @sounds如何设置?
  • @spickermann 对于这个例子 - @sounds = Sound.approved.last(10)
  • @romnoks 当sound 没有image 时你想做什么?你可以在范围内完全跳过它们(例如Sound.where.not(image: nil)...),或者只在那个循环中跳过它们(- next unless sound.image),或者使用占位符图像(也许在Sound#image中定义这种行为?),......或者也许添加所有声音都必须有图像的验证规则?
  • 事实上sound.image 不是nil。只有在注册sound.image.urlsound.image.public_url 方法时才会调用该错误。因此,我不能提出这么简单的条件。
  • 也许我需要编写自己的异常来处理它?

标签: ruby-on-rails ruby exception gcloud


【解决方案1】:

好像在某些情况下会出现错误ActionView::Template::Error (undefined method `public_url' for nil:NilClass)

查看社区,似乎有一些选项/方法可以修复此错误,这取决于您的代码和应用程​​序的配置方式。因此,我建议您查看以下帖子和答案,以检查它们是否对您有所帮助。 :)

如果这些信息对您有帮助,请告诉我!

【讨论】:

    猜你喜欢
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多