Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
p.matsinopoulos Avatar asked Jul 28 '15 15:07

p.matsinopoulos


People also ask

What is require_ tree in rails?

js file. The require_tree directive tells Sprockets to recursively include all JavaScript files in the specified directory into the output. These paths must be specified relative to the manifest file.

How does rails asset pipeline work?

The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB. Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets.

What is Asset_path?

asset_path(source, options = {}) public. This is the entry point for all assets. When using the asset pipeline (i.e. sprockets and sprockets-rails), the behavior is “enhanced”.


1 Answers

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'
like image 53
thunder Avatar answered Oct 01 '22 17:10

thunder