如何在Controller层上使用Rails image_url helper以便它返回正确的值?

时间:2015-07-28 15:06:35

标签: ruby-on-rails asset-pipeline assets ruby-on-rails-4.1

我正在尝试从控制器中调用image_url(来自ActionView::Helpers::AssetUrlHelper模块)。我的控制器是一个API控制器,可以呈现json响应。因此,控制器准备对象,我使用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返回值:

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

而不是

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

请注意,当我在实际视图中使用image_url时,该方法会返回正确的值。

如何在Controller层上使用image_url方法,以便返回正确的值?

2 个答案:

答案 0 :(得分:12)

You should use:

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

and remove the inclusion of the module ActionView::Helpers::AssetUrlHelper

Also, make sure that you have set the action_controller.asset_host value in your environment configuration file. So, for your production environment it should be in config/environments/production.rb and it has to be like

config.action_controller.asset_host='myhost.com'

答案 1 :(得分:1)

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

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"`