Issue showing images in RubyOnRails 4 - ruby-on-rails

I'm working on Rails 4 project that I need to store some images uploadaded directly by the users, and I must be capable of create a images gallery where a single user can only view their own uploads.
I'm uploading files with the CArrierWave gem, and it's doing fine. I'm changed the default uploads directory ( the public folder ) to a custom folder of mine ( /uploads/.....), but I think I'll not be able to show the images cause the 'uploads' folder can't be accessed directly, but I dont want to let the images on the public folder cause I don't want them to be freely accessed by anyone.
Code of my view
<div>
<%= #photos.each do |p| %>
<div>
<%= image_tag (p.path_url) %>
</div>
<% end %>
</div>
My CarrierWave uploader class:
class PhotoupUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"../app/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.album_id}"
end
and Photo model:
class Photo < ActiveRecord::Base
belongs_to :album
attr_accessible :legend, :path
mount_uploader :path, PhotoupUploader
end
How can I proceed?
Thanks

You would need to serve your images straight from the controller (see this question on how: Rendering an image):
def image
render :text => open(File.join('/uploads', user_id, params[:image_id], "rb").read
end
Usage:
<% image_tag "image?image_id=154" %>

Related

ActiveStorage has_many_attached incorrect storage location when inside of transaction

Messing with active storage for the first time. My has_one_attached setups work fine, however my has_many_attached is giving me issues both rendering the file and an incorrect download link:
# frozen_string_literal: true
class DocumentCategory < ApplicationRecord
validates :name, presence: true
has_many_attached :documents
end
seeds file:
DocumentCategory.create!(name: "Governing Documents")
file = Rails.root.join("spec/fixtures/test.png")
DocumentCategory.first.documents.attach(io: File.open(file), filename: "Random File")
view:
<% #document_category.documents.each do |file| %>
<li class='py-2 text-[14px] text-[#3182E2]'>
<div>
<%= link_to file.filename, rails_blob_path(file, disposition: 'attachment') %>
<%= image_tag file, class: 'w-full h-48 mb-1 object-cover'%>
</div>
</li>
<% end %>
For each document in the category, the image is missing, and if I click the link, it opens a new tab to a file that doesn't exist. I'm doing the same thing for each file in the loop to my singular has_one_attached on my other models.
EDIT
This turned out to be due to an existing issue with calling attach multiple times within a transaction, and I had my seeds wrapped in an active record transaction block. Removing the transaction fixed the issue.
https://github.com/rails/rails/issues/41661

Get path to ActiveStorage file on disk

I need to get the path to the file on disk which is using ActiveStorage. The file is stored locally.
When I was using paperclip, I used the path method on the attachment which returned the full path.
Example:
user.avatar.path
While looking at the Active Storage Docs, it looked like rails_blob_path would do the trick. After looking at what it returned though, it does not provide the path to the document. Thus, it returns this error:
No such file or directory # rb_sysopen -
Background
I need the path to the document because I am using the combine_pdf gem in order to combine multiple pdfs into a single pdf.
For the paperclip implementation, I iterated through the full_paths of the selected pdf attachments and load them into the combined pdf:
attachment_paths.each {|att_path| report << CombinePDF.load(att_path)}
Use:
ActiveStorage::Blob.service.path_for(user.avatar.key)
You can do something like this on your model:
class User < ApplicationRecord
has_one_attached :avatar
def avatar_on_disk
ActiveStorage::Blob.service.path_for(avatar.key)
end
end
I'm not sure why all the other answers use send(:url_for, key). I'm using Rails 5.2.2 and path_for is a public method, therefore, it's way better to avoid send, or simply call path_for:
class User < ApplicationRecord
has_one_attached :avatar
def avatar_path
ActiveStorage::Blob.service.path_for(avatar.key)
end
end
Worth noting that in the view you can do things like this:
<p>
<%= image_tag url_for(#user.avatar) %>
<br>
<%= link_to 'View', polymorphic_url(#user.avatar) %>
<br>
Stored at <%= #user.image_path %>
<br>
<%= link_to 'Download', rails_blob_path(#user.avatar, disposition: :attachment) %>
<br>
<%= f.file_field :avatar %>
</p>
Thanks to the help of #muistooshort in the comments, after looking at the Active Storage Code, this works:
active_storage_disk_service = ActiveStorage::Service::DiskService.new(root: Rails.root.to_s + '/storage/')
active_storage_disk_service.send(:path_for, user.avatar.blob.key)
# => returns full path to the document stored locally on disk
This solution feels a bit hacky to me. I'd love to hear of other solutions. This does work for me though.
You can download the attachment to a local dir and then process it.
Supposing you have in your model:
has_one_attached :pdf_attachment
You can define:
def process_attachment
# Download the attached file in temp dir
pdf_attachment_path = "#{Dir.tmpdir}/#{pdf_attachment.filename}"
File.open(pdf_attachment_path, 'wb') do |file|
file.write(pdf_attachment.download)
end
# process the downloaded file
# ...
end

Changing cloudinary file default url per uploader

I have a Rails 4 app with Ruby 2.2.0.
I am building an app for where I need to store quite a bit of images. Currently the app exists and is managing their images on a local server, however we want to change that.
The app is currently deployed on Heroku and we want to use the Cloudinary service to upload(using carrierwave) new images as well as to store the already existing ones.
The issue comes from the fact that I can't seem to be able to adopt the current folder structure that the platform is using. To start with I uploaded all my files via the Media manager in cloudinary dashboard. I created two folders header and logo. In this case I will refer to the header folder as example.
class BannerUploader < CarrierWave::Uploader::Base
include Cloudinary::CarrierWave
def store_dir
"uploads/header/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
The model:
class CompanyImage < ActiveRecord::Base
mount_uploader :file_name, BannerUploader
belongs_to :company
end
And last but not least, here is my view:
<%
work_advantages = company.presentation.work_advantages
banner = company.company_images.where(header: true).first
%>
<%= link_to company do %>
<div class="card company-presentation-card card-hover">
<div class="card-container">
<div class="row">
<div class="col-md-12">
<div class="cover-image">
</div>
<h3><%= company.name %></h3>
<% company.company_sectors.each do |s| %>
<span class="h4-alt1 company-sector"><%= s.sector.name %></span>
<% end %>
<p><%= truncate(company.presentation.work_advantages, :length => 250) %> <span class="text-muted">(lees meer)</span></p>
</div>
</div>
</div>
</div>
<% end %>
<script>
//Set dynamic background image for the cover-image <div>
$(document).ready(function(){
$('.company-presentation-card').find('.cover-image').css('background-image', 'url("<%= banner.file_name %>")')
});
</script>
Currently, the url that is being delivered in the following: http://res.cloudinary.com/hxwmb9swy/image/upload/5a444a7c191e8c98999f6d0c2d3afaf9_Arendsen_Machinefabriek.jpg however I need to have the header(the folder I created in Cloudinary) folder in there so the url should actually look like this: http://res.cloudinary.com/hxwmb9swy/image/upload/header/5a444a7c191e8c98999f6d0c2d3afaf9_Arendsen_Machinefabriek.jpg
Of course in the case of the logo, its exactly the same however instead of header it should say logo. This will also apply to other models. So my question is how can I manage this in a way, so that I can specify this folder per uploader? Any ideas are welcome.
The header or logo should be included in the image's public ID. So if you do a server-side upload, you can override the public_id method in your uploader to include the folder. For example, the following sets the public ID as the header folder with the original image's filename (without the extension, as it should):
def public_id
basename = File.basename(original_filename, File.extname(original_filename))
"header/#{basename}"
end
If you do a client-side upload, with Cloudinary's cl_image_upload for example, you can do something like:
<%= f.cl_image_upload(:image, :folder => "header") %>
For the 2nd case, there's no need to change anything in your Uploader.
Create custom name folder Cloudinary with CarrierWave
include Cloudinary::CarrierWave
def public_id
return "my_folder/" + Cloudinary::Utils.random_public_id;
end

Direct Uploads to S3 using Carrierwave

I've recently converted the below from using Paperclip to Carrierwave uploading to Amazon S3 so I can make use of the carrierwave_direct gem and then Sidekiq or another background processing gem.
class Release < ActiveRecord::Base
has_many :releases_tracks, :dependent => :destroy
has_many :tracks, :through => :releases_tracks, :order => "releases_tracks.position DESC"
accepts_nested_attributes_for :tracks, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => :true
accepts_nested_attributes_for :releases_tracks
end
class Track < ActiveRecord::Base
mount_uploader :track, TrackUploader
has_many :releases_tracks, :dependent => :destroy
has_many :releases, :through => :releases_tracks
end
/views/releases/track_upload.html.erb
<%= form_for(#release, :html => { :multipart => true }) do |f| %>
<h3>Upload Tracks for <%= #release.title %></h3>
<% index = 0 %>
<%= f.fields_for :tracks do |builder| %>
<%= #release.tracks[index].name %>
<%= f.file_field :track, :class => "file styled", :title => 'Select Track'%>
<% index += 1 %>
<% end %>
<%= f.submit "Upload Tracks", :class => "submit" %>
<% end %>
Carrierwave uploads are working, but I can't figure out how to get the direct part working. Partly because I can't figure out how to incorporate the suggested form code:
<%= direct_upload_form_for #uploader do |f| %>
<%= f.file_field :track %>
<%= f.submit %>
<% end %
Or the where in my track OR release controller I place the suggested:
#uploader = User.new.track
#uploader.success_action_redirect = new_user_url
The readme https://github.com/dwilkie/carrierwave_direct and Railscast http://railscasts.com/episodes/383-uploading-to-amazon-s3 both point towards uploading your file first and then creating your database entry. In my app the db entries already exist. The Railscast does say it's possible but doesn't go through it. So that's the first problem.
The second is that I need to upload more than one file at a time. The code above does achieve that, but very slowly and it of course renders my app pretty useless as it does so.
Can anyone help? Massive thanks in advance!
First of all I would advise you not to use carrierwave_direct, I really don't like this gem, for many reasons.
One of those reasons, is that as it's said in the docs
Please be aware that this gem only supports single
file uploads. If you want to upload multiple files simultaneously
you'll have to use a javascript or flash uploader.
But if you want to use it, here is what I guess you have to do :
So first about the
#uploader = User.new.track
#uploader.success_action_redirect = new_user_url
It seems you are trying to upload tracks, and as you said your models have already been created, I guess your are trying to upload new tracks for an existing release. Correct me if I'm wrong.
so you should create the #uploader var in the #track_upload method of your ReleasesController.
class ReleasesController
...
def track_update
#uploader = User.new.track
#uploader.success_action_redirect = new_user_url
end
...
end
then in the associated view (/views/releases/track_upload.html.erb), you can use the direct_upload_form
<%= direct_upload_form_for #uploader do |f| %>
<%= f.file_field :track %>
<%= f.submit %>
<% end %>
The form will upload the file directly to s3, just after you selected the file. Then I don't know exactly how, but carrierwave_direct should give you back the url of the uploaded file.
I'm not sure about that as I've never been that far with it, but the idea is that your file just got uploaded to s3, now it has to be linked to your model, so the file doesn't get 'lost'.
So maybe carrierwave_direct is doing things on its own (I doubt that ...) by doing some ajax requests or anything else.
Anyway as you want to upload more than one file, I'd like to point you to a tutorial I recently wrote
This shows how to upload files directly to s3, without carrierwave_direct, but by doing things on your own. This requires a little bit more code and time, but you have more control about what's happening.
In your case, you'll want to put the form I'm using in my tutorial in your view, in the /views/releases/track_upload.html.erb view.
Then once you'll select a file, the successful AJAX request(emitted by the jQueryFileUpload plugin) will give you the URL of the uploaded file so you can save it in your Track model (you'll probably want to emit a new AJAX request to your server to create the new Track model, or to populate an other form on the page, like the one you were using in the /views/releases/track_upload.html.erb file, and then the tracks will be saved on submit.)
I'm not sure I'm really clear about that, let me know if you need more explanations.
And the good thing about that is that if you simply add multiple to your file input, then the awesome jQueryFileUpload plugin will send a request per file to s3, then you'll get the URL's of the uploaded files in each ajax results :D
And you can tweak things to add progress bars, and things like that with the jQuery plugin, you can really create awesome things.
Hope it'll help you !

Rails: Uploading Images to Amazon S3 via Carrierwave only works on "Edit"

(An Image belongs to a Post)
The image uploader works, but only when I upload the image on Post Edit. I want the image to upload as the Post is created.
The Image upload ("<%= f.file_field :image %>") is within the New Post Form, so I'm guessing Carrierwave is trying to upload the image to the designated path before the Post is created, causing it to not know where to upload.
Here is the ImageUploader file:
class TrackImageUploader < CarrierWave::Uploader::Base
def cache_dir
"#{Rails.root}/tmp/uploads"
end
include CarrierWave::RMagick
#storage :file
#storage :fog
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :featured do
process :resize_to_fill => [210, 145]
end
def extension_white_list
%w(jpg jpeg gif png)
end
end
I am guessing the store_dir from the code above is in charge of saving the image in the according path on Amazon S3.
How would I make it so that it uploads the image AFTER the Post is made, so that it can get the Post.id ?
I had exactly the same problem, but I've found a solution.
My ImageUploader.rb looks like this: https://gist.github.com/egbertp/7572501. On line 9 of this file you'll see include CarrierWaveDirect::Uploader. By using the direct uploader technique, your site-user will upload his/her file directly to the Rackspace cloud. However, at the time of uploading, the Image model is not yet created in you database, causing an error (as you guessed correctly).
By disabling the direct upload technique, the site-user sends the image to your webserver fist and afterwards the Image model is created and saved in the database. In my ImageUploader class this is also necessary because I would like my webserver to process the image, in order to create a thumbnail version.
I hope this will help you, or somebody else in the future.
Best regards,
Egbert
I ve also done the same but i ve used the cloudinary gem to maintain my images. Can you please show me ur controller where u ve written the edit action.
I m showing you my code u can tally it with urs
in the controller in edit action
def create
#img = Image.new(params[:img])
if #img.save
redirect_to(:action => 'show')
else
render('c_view')
end
end
in the view from where it is taking the image
<%= form_for :img, :url => {:action => "create"} do |f| %>
<%= f.label "Upload an image"%>
<%= f.hidden_field(:image_cache)%>
<%= f.file_field :image %>
<%= f.submit "Submit", class: "btn btn-success"%>
<% end %>
To show the image in some view page ive used this
<% #img.each_with_index do |i|%>
<%= image_tag (i.image.url) %>
<%end%>

Resources