Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How to get image path in Controller?

To get the image path in Controller I use the following method:

class AssetsController < ApplicationController
  def download(image_file_name)
    path = Rails.root.join("public", "images", image_file_name).to_s
    send_file(path, ...)
  end
end

Is there a better method to find the path ?

like image 899
Misha Moroshko Avatar asked Jun 29 '11 10:06

Misha Moroshko


2 Answers

ActionController::Base.helpers.asset_path('missing_file.jpg')

Access Asset Path from Rails Controller

like image 87
deefour Avatar answered Nov 02 '22 19:11

deefour


Not sure if this was added as early as Rails 3, but is definitely working in Rails 3.1. You can now access the view_context from your controller, which allows you to call methods that are normally accessible to your views:

class AssetsController < ApplicationController
  def download(image_file_name)
    path = view_context.image_path(image_file_name)
    # ... use path here ...
  end
end

Note that this will give you the publicly accessible path (e.g.: "/assets/foobar.gif"), not the local filesystem path.

like image 24
Matt Huggins Avatar answered Nov 02 '22 20:11

Matt Huggins