Link to local files

I have a small rails system I am building. Part of the code allow
uploading files in to

RailsRoot/public/files folder

I am running this system is several places that have different domain
and folder combinations.


1) # where folder_a is a symbolic link from
Apache document root to the public folder of rails app
2) # where folder_b is the root of the
rails app directly in the Apache document root
3) # where I have set up a virtual host to point directly
to the rails application root

If I have uploaded a file called test.doc, I would like to create a
link from my rhtml template to the file that works where in which ever
domain setup variation you see above.

How can I use link_to or something to create the following correct
links for href= attribute in my link for each case above

for each case the correct Absolute links for file.doc should be:


of course I can't use relative links

for in the case of domain setup 1)

link_to ("your file","files/test.doc") just goes to
link_to ("your file","/files/test.doc") just goes to
test.doc << back to domain base ignoring folder_a

Well, after some experimenting, I have a cluge to find the URL path up
to the Rails Base:

      s = "#{url_for(:controller => 'xxx')}" # create url to fake
controller to just to get full path
      @base_url = s.match(/(.*)\/xxx/)[1] # then find the part of the
path up to /xxx

# @base_url now has the correct path as the app moves to different

now I can use something like

<%= link_to("your file","#{@base_url}/files/#{@filename}") %>
domain setups.

I hate this kind of code. Someone have a clean way?

Found simple way of solving the problem by examining how image_tag

use request.relative_url_root: if your URL to your rails root is then

request.relative_url_root will return /path1/path2

By combining this with link_to or image_tag, you can create links that
will work with any configuration of server url path to your rails app:


<%= link_to("your file2", request.relative_url_root+'/
files/'+@filename) %>
<%= image_tag(request.relative_url_root+'/files/'+@filename)%>