Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carrierwave: Argument Error Nil location provided. Can't build URI for an image_tag using carrier wave Ruby on Rails

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' %>
like image 602
Sachin Avatar asked Nov 27 '18 23:11

Sachin


3 Answers

This error is because image_tag argument is nil:

<%= image_tag nil %> # Nil location provided. Can't build URI
like image 86
Abel Avatar answered Sep 18 '22 14:09

Abel


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
like image 29
mrzasa Avatar answered Sep 17 '22 14:09

mrzasa


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

like image 38
Promise Preston Avatar answered Sep 17 '22 14:09

Promise Preston