12

I'm getting an argument error for Nil location provided when using the image_tag. How do I make the image_tag optional where it only displays if there is a corresponding image? This is with Ruby on Rails 5.

This is my current show page view:

<p id="notice"><%= notice %></p>

<%= image_tag @restaurant.image_url %>

<p>
  <strong>Name:</strong>
  <%= @restaurant.name %>
</p>

<p>
  <strong>Address:</strong>
  <%= @restaurant.address %>
</p>

<p>
  <strong>Phone:</strong>
  <%= @restaurant.phone %>
</p>

<p>
  <strong>Website:</strong>
  <%= @restaurant.website %>
</p>

<%= link_to 'Edit', edit_restaurant_path(@restaurant), class: 'btn btn-link' %> |
<%= link_to 'Back', restaurants_path, class: 'btn btn-link' %>
Promise Preston
  • 24,334
  • 12
  • 145
  • 143
Sachin
  • 257
  • 1
  • 3
  • 15

4 Answers4

21

You have two options.

1) Render image tag only if there is an image to be shown:

 <% if @restaurant.image_url %>
    <%= image_tag @restaurant.image_url %>
 <% end %>

2) Provide a default value for image_url field:

 <%= image_tag @restaurant.image_url || default_image %>

It's better to do it in a model/presenter:

class Image < ApplicationModel

  def image_url
    super || default_image
  end
end

Or with attribute API:

class Image < ApplicationModel
  attribute :image_url, default: default_image
end
mrzasa
  • 22,895
  • 11
  • 56
  • 94
2

Just to add to the answers.

You can use a one-liner code for this:

<%= image_tag(@restaurant.image_url) if @restaurant.image_url%>

which is equivalent to:

<% if @restaurant.image_url? %>
  <%= image_tag(@restaurant.image_url) %>
<% end %>

OR

<% if @restaurant.image_url? %>
  <%= image_tag @restaurant.image_url %>
<% end %>

Resources: Carrierwave - Making uploads work across form redisplays

That's all.

I hope this helps

Promise Preston
  • 24,334
  • 12
  • 145
  • 143
1

This error is because image_tag argument is nil:

<%= image_tag nil %> # Nil location provided. Can't build URI
Abel
  • 3,989
  • 32
  • 31
0

use if condition, if there is an image it will display, if none, no error

   <% if @restaurant.image_url? %>
     <%= image_tag @restaurant.image_url %>
   <% end %>
Fenet
  • 1