Rails 5, "nil is not a valid asset source"
Asked Answered
F

4

23

I have just upgraded to Rails 5 and I have a weird issue while trying to show an image.

I have the exact code I had for Rails 4:

<%= image_tag article.image_url(:thumb) %>

But after upgrading I get:

nil is not a valid asset source

Before upgrading to Rails 5, I didn't have any similar issue.

What could be at fault here? Can it be something else and not a Rails upgrade issue?

Fundy answered 30/5, 2016 at 16:18 Comment(1)
It looks like you just don't have an image in this record. Could you confirm it?Pell
F
28

The problem was that I was trying to show an image that did not exist.

Adding unless article.image.blank? solved it:

<%= image_tag article.image_url(:thumb) unless article.image.blank? %>

EDIT: In Rails 4, this would have just rendered nothing without errors, while in Rails 5 it raises an error. So it was, in fact, an upgrade issue.

Big thanks to @BookOfGreg for pointing this out.

Fundy answered 25/7, 2016 at 12:15 Comment(6)
For those getting here without carrierwave: In rails 4, this would have rendered out an empty img tag, in rails 5 it will raise on nil, so there is a small difference.Becerra
In solidarity. .Goggle
Ibid. Also, default images not present will raise this error in Rails 5 and it can take a fair bit of hunting to find the cause.Morrissette
If you still need to create an <img> tag even if the image is not available, you can use content_tag(:img, nil, src: "...", alt: "...") (maybe because you set its source with JavaScript later).Interrupter
it is better to avoid unless. The above code can be changed to <%= image_tag article.image_url(:thumb) if article.image.present? %>Artificer
@ViC I think in this case it is exactly the same using unless...blank and if...present. It would be bad to use unless if we had something like unless...!blank which makes the person reading the code to think in double negationFundy
C
10

I don't know this is compact solution or not but this code will work.

activate the fallback method in your uploader.

  def default_url
    "/assets/fallback/" + [version_name, "default.png"].compact.join('_')
  end

Hope this will help you.

Cheers (y)

Cho answered 24/7, 2016 at 12:31 Comment(1)
I already solved it, but I forgot to update this post. Thank you anyway.Fundy
B
0

Try with this, you need to add unless condition in your code. You need to add below code

<%= image_tag article.image_url(:thumb) unless article.image.blank? %>

Belemnite answered 19/9, 2016 at 7:14 Comment(0)
P
0

I hope this code snippet will help those future readers.

<td><%= image_tag image.picture.url, size: "100x100" unless image.picture.url.blank? %></td>

without that unless image.picture.url.blank? part of the code,

"nil is not a valid asset source"

shows up when uploading empty image.

Phenyl answered 6/6, 2018 at 3:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.