如何在 Controller 层上使用 Rails image_url 助手,使其 returns 成为正确的值?

How can I use Rails image_url helper on the Controller layer so that it returns the correct value?

我正在尝试从控制器中调用 image_url(来自 ActionView::Helpers::AssetUrlHelper 模块)。我的控制器是一个呈现 json 响应的 API 控制器。因此,控制器准备对象,我正在使用 jBuilder 来呈现实际的 JSON 响应。这是代码:

class Api::Mobile::HomeController < Api::Mobile::ApplicationController
  include ActionView::Helpers::AssetUrlHelper

  def index
    @items = [Api::Mobile::HomePageItem.new(
                type: 'image',
                image: image_url("api/mobile/home/tutor-with-student.jpg"))]
  end
end

图像 tutor-with-student.jpg 存在于以下文件夹中:

app/assets/images/api/mobile/home/tutor-with-student.jpg

问题是 image_url returns 值:

http://myhost.com/images/api/mobile/home/tutor-with-student.jpg

而不是

http://myhost.com/assets/api/mobile/home/tutor-with-student.jpg

请注意,当我使用 image_url 从实际来看,方法 returns 是正确的值。

如何在 Controller 层使用 image_url 方法使其 returns 正确值?

你应该使用:

ActionController::Base.helpers.asset_url("api/mobile/home/tutor-with-student.jpg", type: :image)

并删除模块的包含 ActionView::Helpers::AssetUrlHelper

此外,请确保您已在环境配置文件中设置 action_controller.asset_host 值。因此,对于您的生产环境,它应该在 config/environments/production.rb 中并且必须像

config.action_controller.asset_host='myhost.com'

感谢之前的作者。我不确定性能,但这种方法对我有帮助:

def logo_url
    host_url = request.path == '/' ? request.url : request.original_url.split(request.path).first
    asset_path = ActionController::Base.helpers.asset_url('logo.png')
    host_url + asset_path
end
# will return
=> "http://localhost:3000/assets/logo-40e3bf1e10f0c00393ac94f96ea127986955c166eb839266eb2ad6e63b42754c.png"`