24

I have a rails 3.x application that has model classes which return content to a view partial to be rendered on a page. The model takes care of what the content is and just returns it to the view which blindly adds it to the page. In other words, the view calls the model asking for its content; the model delivers its content HTML-Safe to the view; and the view just dumps what is returned into into its output.

Thus far, everything works.

I need to make such a class that returns the html for a link to an image in the asset pipeline (the view does not know or care that the thing being returned is an image).

In it's simplest form, the model reads a record from the database which contains a filename, "my_image.png". It needs to return to the view the HTML referring to the image with that name that is located in "app/assets/images".

Is it possible to do this ?

starfry
  • 9,273
  • 7
  • 66
  • 96

2 Answers2

70

This will work inside Model

ActionController::Base.helpers.image_tag("image.png")
PradeepKumar
  • 1,259
  • 9
  • 5
  • you star, this fixed an issue I was having where `image_tag` wasn't working in helper methods – TomDunning Mar 23 '15 at 14:07
  • Cool man, I define a helper method using the line you provided and then i just call that method instead of using image_tag in slim. – Travis Le Jan 10 '19 at 08:50
3

try including helper in model include ActionView::Helpers & ActionView::Helpers::AssetTagHelper

Amar
  • 6,874
  • 4
  • 25
  • 23
  • I had been trying to include things like ActionView::AssetPath, ActionView::Helpers and ActionView::Helpers::AssetTagHelper but it kept just throwing errors... – starfry Aug 24 '12 at 12:27