【问题标题】:Carrierwave: Argument Error Nil location provided. Can't build URI for an image_tag using carrier wave Ruby on RailsCarrierwave:提供参数错误无位置。无法使用载波 Ruby on Rails 为 image_tag 构建 URI
【发布时间】:2019-04-29 19:20:12
【问题描述】:

我在使用 image_tag 时收到 Nil 位置的参数错误。如何使 image_tag 可选,仅在有相应图像时才显示?这与 Ruby on Rails 5 一起使用。

这是我当前的显示页面视图:

<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' %>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 carrierwave


    【解决方案1】:

    你有两个选择。

    1) 仅当有图片要显示时才渲染图片标签:

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

    2) 为image_url 字段提供默认值:

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

    最好在模型/演示者中进行:

    class Image < ApplicationModel
    
      def image_url
        super || default_image
      end
    end
    

    或者attribute API:

    class Image < ApplicationModel
      attribute :image_url, default: default_image
    end
    

    【讨论】:

    • 对我也很有帮助。
    • 它工作的人。我会选择创建一个辅助方法的解决方案,然后在我想要的任何地方调用它:D
    【解决方案2】:

    使用if条件,如果有图片则显示,如果没有则无错误

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

    【讨论】:

      【解决方案3】:

      只是为了补充答案。

      您可以为此使用单行代码:

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

      相当于:

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

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

      资源Carrierwave - Making uploads work across form redisplays

      就是这样。

      我希望这会有所帮助

      【讨论】:

        【解决方案4】:

        这个错误是因为 image_tag 参数为 nil:

        <%= image_tag nil %> # Nil location provided. Can't build URI
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多