【发布时间】: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.url或sound.image.public_url方法时才会调用该错误。因此,我不能提出这么简单的条件。 -
也许我需要编写自己的异常来处理它?
标签: ruby-on-rails ruby exception gcloud