This describes how to create links to static content in a way that works whether or not your app is installed directly at document root, and under other web servers than Webrick.
In a Rails app, static content is placed under the public subdirectory. Images, Javascripts, and stylesheets are stored in the public/images, public/javascripts, and public/stylesheets subdirectories.
When running under Webrick, files under the public directory can be accessed using an absolute URL, as in
<img src="/images/someimage.gif"/>
However this doesn’t work if your app is installed somewhere other than document root, or if running under some other web server than Webrick where you want the web server to handle static content. For example, if your Rails app is running under Apache/FCGI, and is installed at /yourapp under document root, then the correct URL for your image would need to be
<img src="/yourapp/public/images/someimage.gif"/>
Luckily, Rails has some helpers to generate the correct URL automatically regardless of the environment your app is running under.
image_tag, javascript_include_tag, and stylesheet_link_tag helper functions respectively. See the ActionView::Helpers::AssetTagHelper documentation. For example, to generate the above image tag, you’d write:<%= image_tag “someimage.gif” %>
def link_to_file(name, file, *args)
if file0 != ?/
file = “#{@request.relative_url_root}/#{file}”
end
link_to name, file, *args
end
<%= link_to_file “Installer Program”, “installer.exe” %>
Installer Program
Installer Program
QUESTION: Is this any different than link_to ?
QUESTION: What about using url_for with a :controller that is the path to the static content?
<%= url_for :controller => ‘/flash/show.swf’ %>