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?
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.
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.
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”.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With