Rails 4.2升级:传递给帮助者的资产名称不应包括" / assets /"字首

时间:2016-10-19 16:35:32

标签: ruby-on-rails

我从Rails 4.1升级到4.2。我现在收到以下错误:

Sprockets::Rails::Helper::AbsoluteAssetPathError at /

Asset names passed to helpers should not include the "/assets/" prefix. Instead of "/assets/spinner.gif", use "spinner.gif"

错误消息很明确。但是,我不知道它在说什么。它强调了这一行代码:

  <div class="loading">
    <%= image_tag asset_path('spinner.gif') %>
  </div>

我不使用文字字符串&#39; / assets /&#39;在那行代码中。那么这个错误指的是什么?

我可以通过移除对asset_path的调用并使用image_tag 'spinner.gif'来解决该特定错误;但是,我仍然在这里得到错误(我正在使用Paperclip gem):

<%= image_tag current_user.avatar.url(:thumb) %>

由此引起:

ActionController::Base.helpers.asset_path('missing-user.png')

再次,它抱怨asset_path。

更新:

仅当我将asset_path传递给image_tag方法时才会出现错误:

ActionController::Base.helpers.asset_path('missing-user.png')
 => "/assets/missing-user.png" 

helper.image_tag(ActionController::Base.helpers.asset_path('missing-user.png'))
Sprockets::Rails::Helper::AbsoluteAssetPathError: Asset names passed to helpers should not include the "/assets/" prefix. Instead of "/assets/missing-user.png", use "missing-user.png"

2 个答案:

答案 0 :(得分:0)

我解决了这个问题,但我仍然不了解WHY因素。这只发生在我从Rails 4.1升级到4.2时。看看这个:

ActionController::Base.helpers.asset_path('missing-user.png')
 => "/assets/missing-user.png" 

helper.image_tag "/assets/missing-user.png"   
Sprockets::Rails::Helper::AbsoluteAssetPathError: Asset names passed to helpers should not include the "/assets/" prefix. Instead of "/assets/missing-user.png", use "missing-user.png"

helper.image_tag "missing-user.png"  
 => "<img src=\"/assets/missing-user.png\" alt=\"Missing user\" />" 

基于以上所述,image_tag不希望您将文字路径字符串&#39; assets&#39;传递给它。因此,在我的Paperclip gem帮手中,我不得不这样做:

 has_attached_file :avatar,
                    styles: { normal: "128x128>", thumb: "40x40>" },
                    default_style: :thumb,                     
                    default_url: ->(attachment) { 'missing-user.png' }

换句话说,我不得不删除它:

 ActionController::Base.helpers.image_url('missing-user.png')

因为image_url返回字符串&#39; /assets/missing-user.png'。

答案 1 :(得分:0)

image_tag会自动将源选项传递给asset_path

image_tag("icon")
# => <img alt="Icon" src="/assets/icon" />
image_tag("icon.png")
# => <img alt="Icon" src="/assets/icon.png" />
image_tag("/icons/icon.gif", height: '32', width: '32')
# => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />

因此,当您致电image_tag asset_path('spinner.gif')时,您实际上正在执行image_tag( '/assets/spinner.gif' ),这就是您收到链轮警告的原因。