Rails4: image_url not generating digest in controller

时间:2016-04-04 17:59:47

标签: ruby-on-rails assets sprockets

I have this code:

class ExampleController < ApplicationController
  include ActionView::Helpers::AssetUrlHelper

  def show
    respond_to do |format|
      msg = { status: "ok", message: "Success!", image_url: image_url('image.png') }
      format.json  { render :json => msg }
    end
  end
end

This return me this response:

{ status: "ok", message: "Success!", image_url: 'images/image.png' }

And I expect something like:

{ status: "ok", message: "Success!", image_url: 'assets/image-37bf76be1.png' }

What is the problem?

2 个答案:

答案 0 :(得分:2)

如果您想从控制器渲染图像,我相信您需要使用view_context.image_url

答案 1 :(得分:1)

正如born4new建议的那样,您需要使用image_url来正确引用资产管道中的图像。 但是,我不建议在此处使用资产管道。请注意,在预编译资产时,资产摘要网址可能会发生变化。由于您从API提供此值,这意味着您在重新编译资产时会使用可能会呈现404的网址进行回复。

相反,您应该考虑将图像作为public/文件夹中的静态资源提供。这样,在重新部署或重新生成资产后,API的任何使用者都可以可靠地访问这些文件。

相关问题