Search code examples
ruby-on-railsasset-pipelineassetsruby-on-rails-4.1

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


I am trying to call image_url (from the ActionView::Helpers::AssetUrlHelper module) from within a controller. My controller is an API controller that renders a json response. So, the controller prepares the object and I am using jBuilder to render the actual JSON response. Here is the code:

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

The image tutor-with-student.jpg exists in the following folder:

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

The problem is that the image_url returns the value:

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

instead of

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

Note that when I am using the image_url from the actual view, the method returns the correct value.

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


Solution

  • 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'