ruby-on-railsrubyruby-on-rails-4activeview

Routing Error: No route matches [GET] /image/my_image.png


I am generating image tags from within one of my models and I can't get Rails to create working URLs in both development and production mode simultaneously. I started out with this in one of my models:

def traffic_light_icon(size=15)
  image_tag "/assets/#{size}/#{traffic_colour}.png"
end

(I'm getting access to image_tag with include ActionView::Helpers::AssetTagHelper.)

This worked fine in development, but in production, the link was not automatically updated with the appropriate hash to take an image from the asset pipeline. If I try to use the form

image_tag "#{size}/#{traffic_colour}.png"

instead (as various sources suggest), then it doesn't even work in development -- I get a Routing Error (No route matches [GET] /image/15/amber.png).

What am I doing wrong?


Solution

  • Basically, the answer is don't use image_tag inside a model, even if you figure out a hack to get access to it. In order to generate a proper context-sensitive URL, the helper needs access to session data that is not available from within models. This results in Rails creating an image tag, but badly, one that won't work in all situations (in my case, in development but not production).

    There is good information about when and how to use helpers inside models and controllers in Railscast 132 (with a few hints as to when not to, or when to look out for problems it causes).