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' %>
This error is because image_tag argument is nil:
<%= image_tag nil %> # Nil location provided. Can't build URI
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With