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 ?
ActionController::Base.helpers.asset_path('missing_file.jpg')
Access Asset Path from Rails Controller
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.
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