wdhilliard
wdhilliard

Reputation: 144

Paperclip :url does not create Routes

What is the point of using the :url option with paperclip? The :path option does in fact change the location where the file is saved, but the :url option doesn't seem to do a thing. It only works when it points to a publicly accessible file location. At that point, the url is already accessible to anyone. If I change the url so that it doesn't match the path, it does not work. As far as I can tell, it does not create any routes either way. Is there something I am missing here. What is the point of this option? It seems overly confusing to let someone specify a :url without actually creating a route.

Upvotes: 0

Views: 541

Answers (1)

Tom Kadwill
Tom Kadwill

Reputation: 1478

I found this post useful in understanding the difference between :path and :url.

  • :path sets the directory in your application where the file is stored.
  • :url sets the url that users can use to access the image.

You are right, paperclip does not create a route for you. However, the :url option does give you the ability to select which (existing) route your users can use to download a specific image.

:path and :url usually go hand in hand. If you stick to the paperclip :default_url the path is already configured for you. Just hit the url and everything will work fine.

Changing the file location

In this example I am rendering a users avatar:

<%= image_tag @user.avatar.url %>

Now, lets say that you wanted to change the location that images are stored, you can add the following code to your model:

  has_attached_file :avatar,
    :path => "public/system/:class/:id/:filename"

However, the image will not render successfully. This is because the new path, where your images are stored, does not match the :default_url. Therefore, you will also need to specify a new url:

  has_attached_file :avatar,
    :path => "public/system/:class/:id/:filename"
    :url => "/system/:class/:id/:basename.:extension"

Now the image url matches the location that the file is stored on your server and the image renders successfully.

Path vs URL

To summarize, :url tells paperclip where abouts on the server to look for an image. :path tells paperclip where to upload an image, when creating or updating a record.

Both :path and :url should point to the same location, in order to render an image successfully.

Upvotes: 3

Related Questions