html img 标签不工作,因为生成了错误的路径 Rails 4

html img tag not working because wrong path generated Rails 4

我的 rails 应用程序中有一个 div 标签 (new.html.erb):

<div style="background: url(images/background.jpg) no-repeat;"> 
</div>

图像没有出现,我收到 ActionController 路由错误 No route matches [GET] "/locations/images/background.jpg"

问题是 Rails 将 locations/ 添加到文件路径,这是错误的,因为我的图片正确位于 app/assets/images/background.jpg. 即使我包含文件的绝对路径,我也会将 locations 添加到它的开头。

这是我的路线(不确定是否有帮助,但不会造成伤害!):

 locations GET    /locations(.:format)          locations#index
              POST   /locations(.:format)          locations#create
 new_location GET    /locations/new(.:format)      locations#new
edit_location GET    /locations/:id/edit(.:format) locations#edit
     location GET    /locations/:id(.:format)      locations#show
              PATCH  /locations/:id(.:format)      locations#update
              PUT    /locations/:id(.:format)      locations#update
              DELETE /locations/:id(.:format)      locations#destroy

您需要在视图中使用 image_path 助手生成 url:

<div style="background-image: url('<%= image_path('background.jpg') %>'); background-repeat: no-repeat">
</div>

助手很重要,因为在生产中您的资产可能会被指纹识别或远程托管(例如在 CDN 上)。助手将始终生成正确的 url.

编辑:

要在 css 文件中引用背景图像,您有两种选择。使用基础 rails,您可以将 .erb 添加到 css 文件名的末尾并使用上述代码替换。

stylesheet.css.erb:

.myclass {
  background-image: url(<%= asset_path 'background.png' %>);
}

或者,如果您使用 sass-rails gem,您可以使用 image-urlasset-url 助手:

stylesheet.scss:

.myclass {
  background-image: image-url('background.png');  // or asset-url('background.png');
}

有关详细信息,请参阅 Asset Pipeline Guide