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?

Tasos Anesiadis
  • 1,134
  • 1
  • 12
  • 37

4 Answers4

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.

Tasos Anesiadis
  • 1,134
  • 1
  • 12
  • 37
  • 7
    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. – BookOfGreg Mar 28 '17 at 08:18
  • 1
    In solidarity. . – Leo Folsom May 31 '17 at 21:37
  • 1
    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. – t56k Sep 20 '17 at 03:14
  • 2
    If you still need to create an `` 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). – Joshua Muheim Jun 09 '18 at 09:48
  • it is better to avoid `unless`. The above code can be changed to `<%= image_tag article.image_url(:thumb) if article.image.present? %>` – Victor Ivanov Jul 04 '18 at 11:45
  • @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 negation – Tasos Anesiadis Jul 05 '18 at 01:33
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)

Simranjit Singh
  • 289
  • 2
  • 10
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? %>

ekad
  • 14,436
  • 26
  • 44
  • 46
Rahul2692
  • 334
  • 1
  • 10
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.

toking
  • 320
  • 2
  • 10