By Default: the paperclip gem stores all attachments within the public directory.
I did not want to store the attachments within the public directory for security reasons, so I saved them within an uploads
directory at the root of the app:
class Post < ActiveRecord::Base
belongs_to :user
has_attached_file :some_image, path: ":rails_root/uploads/:attachment/:id/:style/:filename"
do_not_validate_attachment_file_type :some_image
end
I did not specify the url
option because I do not want a url for each image attachment. If a url is specified: then ANYONE with that url can access the image. This is not secure.
In the user#show
page: I want to actually display the image. If I were using all of the paperclip defaults then I could just do this because the image would be within the public directory and the image would have a url:
<p>
<strong>Some image:</strong>
<%= image_tag @post.some_image %>
</p>
It appears that if I save the image attachments outside the public directory and do not specify a url (again: doing this to secure the image), then the image will not render in the view.
I am aware of how to authorize throughout an application via the pundit gem. However, authorizing for an image is useless when that image is publicly accessible. So I attempt to make the image not publicly accessible by removing the url and saving the image outside the public directory, but then the image no longer renders in the view.
Update: My question really boils down to this: My images are saved within my rails application. With paperclip: is there any way to securely display an image in the view? In other words: Make it so that the image does not have its own separate url (because ANYONE with that url can access that image, making that image not secure). Here are some examples of what I mean by securely displaying the image:
- Example #1: Only display the image if the user is logged in. (The image does not have its own separate url, so there is no other way to access the image)
- Example #2: Only display the image if the user is associated to this image. (The image does not have its own separate url, so there is no other way to access the image)
Additional Update: I am aware that I can securely send a file with send_file
which allows the user to download the image, but that is not what I want to do here. I do not want the user to download the image. Instead: I want the user to be able to actually see the image on the webpage. I want to securely show/render the image on the page. Using send_file
(as I understand it) allows the user to download the file. It does not render the image on the page.
image_tag
, rails just generates an HTML<IMG>
tag, with the src parameter set to the image URL. The browser then will get the image from the server through the URL. Any other way would involve Javascript and be quite complicated (the only simple alternative that I see is what I mentioned in the previous comment, with a provider supporting that). – Portal