Skip to content


Rails Sub URI Headaches with Paperclip

I have a number of Ruby-on-Rails apps on my little Ubuntu server, each one accessible using a sub URI. For example, the home controller of the homework application is accessed with:

http://bravo.local/homework/home

Where homework is the sub URI configured to serve my application and home is the name of one of the controllers. The Apache/Passenger configuration for this set up is documented here.

This approach has worked fine until I used the Paperclip gem in my latest Rails app. I discovered that the attachment links that were being generated started with a slash but did not include the application’s sub URI. To work around this issue I needed some way to append the relevant sub uri to the Paperclip URI. I hate hard coding stuff like this and I wanted something that would work in different environments. I added a

<%= debug request.inspect %>

to one of my views and found that there is a method request#script_name that returns the complete protocol, port, host name and the sub URI. Problem solved! Not quite. I like to keep my views nice and tidy so I construct that URL in a helper. In fact, after watching Ryan Bates’ Rails Casts, I have become a big fan of the decorator gem Draper. Thanks to an email from Jeff Casimir, the author of Draper, I learned that I could access the request object directly from the Draper helper method. Here’s an example:

  def link
    # doc.doc is the Paperclip object
    url = h.request.script_name + doc.doc.url 
    h.link_to doc.description, url
  end

Posted in Linux, Ruby-on-Rails.

Tagged with , , , , , , , , , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.



%d bloggers like this: