Rails: How to download a previously uploaded document? - ruby-on-rails

I need my user to upload documents such ad pdf and txt on their profile. And I did that using Carrierwave, so I have a list of documents with titles and urls.
But how can I make other users download those files? Do I have to use a gem or is there something native I don't even know since I am very new to rails?
Thanks
EDIT:
society.rb
class Society < ActiveRecord::Base
...
has_many :documents, :dependent => :destroy
end
document.rb
class Document < ActiveRecord::Base
belongs_to :society
mount_uploader :url, DocumentUploader
end
And then this in the view I want to download files:
<% #society.documents.each do |doc| %>
<%= link_to "Download it", doc.url %> //url is the column name of the saved url
<% end %>

I don't use Carrierwave but I guess it's similar to Paperclip.
Therefore you should be able to use something like this
link_to 'Download file', user.file.url
This is assuming you have a user instantiated object from a Model with a 'file' carrierwave attribute. Replace this with your attribute name.

You can use the send_file method for this. Which could look like:
class MyController
def download_file
#model = MyModel.find(params[:id])
send_file(#model.file.path,
:filename => #model.file.name,
:type => #model.file.content_type,
:disposition => 'attachment',
:url_based_filename => true)
end
end
Check the apidock link for more examples.

Or you can put anchor tag:
in your controller:
#doc = "query to get the document name from your database"
#docpath = request.base_url+"/uploads/"+#doc
in your view:
<a href="#docpath" download>Download File</a>.

Related

ActiveStorage multiple upload with intermediate model

The goal
I want to upload multiple files. So one Intervention can have multiple Uploads and each Upload has one attached file to it. This way, each Upload can have one file attached with different status, name, visibility, etc. instead of having one Upload with has_many_attached
What I have done
I have one Intervention model that can have many uploads :
class Intervention < ApplicationRecord
has_many :uploads, dependent: :destroy
accepts_nested_attributes_for :uploads, :allow_destroy => true
end
Each uploads has one attached file using ActiveStorage :
class Upload < ApplicationRecord
belongs_to :intervention
has_one_attached :file
end
In my interventions_controller I do :
def new
#intervention = Intervention.new
#intervention.uploads.build
end
def create
#intervention = Intervention.new(intervention_params)
# + default scaffolded controller [...]
end
def intervention_params
params.require(:intervention).permit(:user_id, :comment, uploads_attributes: [:status, :file])
end
In my form I have :
<%= form.fields_for :uploads, Upload.new do |uploads_attributes|%>
<%= uploads_attributes.label :file, "File:" %>
<%= uploads_attributes.file_field :file %>
<%= uploads_attributes.hidden_field :status, value: "raw" %>
<% end %>
Problem
This solution works when I want to upload only one file. But if I want to upload two files I can't figure out. I can add multiple: true to the file_field but how to created multiple Upload with one file each ?
Should I save the uploaded files into a temp variable first, extract them from the intervention_params, then create the Intervention without any Upload, then for each uploaded files saved, build a new Upload for the newly created Intervention ?
I have done what I have proposed. I don't know if there is a more elegant way to do it but anyway, this is working.
In my form I just added a simple files field that can take multiple files
<div class="field">
<%= form.label :files %>
<%= form.file_field :files, multiple: true %>
</div>
I have added this to the permitted parameters :
params.require(:intervention).permit(:user_id, :comment, files:[]])
Then I create my Intervention by ignoring this files params and I use it later to create a new Upload record for each files submitted.
# First create the intervention without the files attached
#intervention = Intervention.new(intervention_params.except(:files))
if #intervention.save
# Then for each files attached, create a separate Upload
intervention_params[:files].each do |f|
upload = #intervention.uploads.new()
upload.file.attach(f)
upload.save
end
end

How to edit multiple attached images using ActiveStorage `has_many_attached` in ActiveAdmin

I have a simple model that can have multiple images attached via ActiveStorage handling the file storage.
I am using ActiveAdmin to edit my model and to upload/attach the images - so far no problems.
The problem is, when I want to edit my model, and add new images, then the previous ones are deleted, and only the new ones added.
I can do a preview of already attached images, and could also delete them separately, but how do I achieve, that by uploading new images, the old ones are NOT deleted?
My model:
class Post < ActiveRecord::Base
has_many_attached :images
end
My ActiveAdmin page:
ActiveAdmin.register AdminPost do
permit_params images:[]
form do |f|
f.input :images, as: :file, input_html: { multiple: true }
if #resource.images.exists?
#resource.images.map do |m|
para image_tag m
end
end
end
end
Assuming you are using rails 6.0+;
you can solve this by adding following code in to your environments (i.e - development.rb )
https://github.com/rails/rails/issues/35817#issuecomment-628654948
config.active_storage.replace_on_assign_to_many = false
in your form,
form do |f|
f.input :images, as: :file, input_html: { multiple: true }
f.object.images.each do |image|
span image_tag(image)
end
end
So I chose the way of adding the new attachments manually, so they don't replace the existing attached images.
I added a field to handle the posted images, and a method to add them in my model.
class Post < ActiveRecord::Base
has_many_attached :images
attr_accessor :new_images
def attach_images
return if new_images.blank?
images.attach(new_images)
self.new_images = []
end
end
And the ActiveAdmin page controller handles the upload, and calls the new method:
ActiveAdmin.register AdminPost do
permit_params new_images:[]
form do |f|
f.input :new_images, as: :file, input_html: { multiple: true }
if #resource.images.exists?
#resource.images.map do |m|
para image_tag m
end
end
end
controller do
after_save :add_images
def add_images(post)
post.attach_images
end
end
end

Cloudinary::CarrierWave how to select the upload folder in Cloudinary

I try to use the module Cloudinary::CarrierWave, but all my images are stored in the root folder of the cloud.
I want all my files to go to a specific remote folder.
I try this in my class:
class PhotoUploader < CarrierWave::Uploader::Base
include Cloudinary::CarrierWave
def storage_identifier
'specific_folder'
end
end
I know there is some options with Cloudinary::Upload.upload, but as I use simple form in ruby on rails, I don't have access to this method.
Does anybody has an idea to fix that ?
When using Carrierwave with server-side uploads, you can use a code like the following:
classPictureUploader < CarrierWave::Uploader::Base
include Cloudinary::CarrierWave
...
def public_id
return "my_folder/" + model.short_name
end
end
If you're using client-side upload, you can set the folder parameter when building the upload tag:
<%= f.cl_image_upload(:image, :folder => "my_folder") %>
thanks to your answer, I solve that with your help, and I can give some other tips.
I did something like this to separate folders, but sometimes model.id doesn't exist (I should add an if else)
def public_id
"artpieces/#{model.class}/#{model.id}"
end
This code doesn't work for me :
<%= f.cl_image_upload(:image, :folder => "my_folder") %>
I can write directly :
<%= f.input :photo, input_html: {accept: ('image') } %>
as my input is already a PhotoUploader declare like this in the model :
mount_uploader :photo, PhotoUploader

Refile gem : multiple file uploads

I'm using Refile with Rails 4. I'm following their tutorial for multiple image upload. Each Post can have multiple Images. My models look like this:
Post.rb:
has_many :images, dependent: :destroy
accepts_attachments_for :images, attachment: :file
Image.rb:
belongs_to :post
attachment :file
I can upload files, fine by using:
<%= f.attachment_field :images_files, multiple: true, direct: true, presigned: true %>
but when I try to retrieve an image like:
<%= attachment_image_tag(#post.images, :file, :small) %>
I get the error:
undefined method file for #<Image::ActiveRecord_Associations_CollectionProxy:0x007fbaf51e8ea0>
How can I retrieve an image with refile using multiple image upload?
In order to retrieve images who belongs to a post, you need to iterate through the array of images.
<% #post.images.each do |image| %>
<%= attachment_image_tag(image, :file, :fill, 300, 300) %>
<% end %>
The helper attachment_image_tag take:
[Refile::Attachment] object : Instance of a class which has an attached file.
[Symbol] name : The name of the attachment column
So here, #posts.images holds an array of image object. It's that object who has an attached file.
class Image < ActiveRecord::Base
belongs_to :post
attachment :file
end
Then when you iterate images, you give to the helper the image object, and the name of the attachment column, here :file.
Are you on the master branch?
gem 'refile', require: "refile/rails", git: 'https://github.com/refile/refile.git', branch: 'master'

upload multiple files through controller using paperclip and rails

I have used the following tutorials:
http://patshaughnessy.net/2009/5/16/paperclip-sample-app-part-2-downloading-files-through-a-controller
This tutorial walks you through downloading files through the controller rather than as static files. I did this to control access to the files.
http://emersonlackey.com/article/paperclip-with-rails-3
This tutorial walks you through the process of creating a model for your files and using that to allow multiple file uploads
So, for the most part I got the uploading to work fine, however, the problem is in the downloading.
A little background. I have the following key models.
class VisualSubmission < ActiveRecord::Base
has_many :assets
accepts_nested_attributes_for :assets, :allow_destroy => true;
end
class Asset < ActiveRecord::Base
belongs_to :visual_submission
has_attached_file :image, :styles => { :original => "100%", :large => "600x600>", :small => "150x150>", :thumb => "50x50>"}, :convert_options => {:all => "-auto-orient"},
:path => ':rails_root/secure/system/:attachment/:id/:style/:basename.:extension',
:url => '/:class/:id/:attachment?style=:style'
end
In order to download files through the controller, an action is created as such:
def images
visual_submission = VisualSubmission.find(params[:id])
style = params[:style] ? params[:style] : 'original'
send_file visual_submission.image.path(style), :type => visual_submission.image_content_type, :disposition => 'inline'
end
So, as I said above, uploading is just fine. One thing that is different but expected, when it stores the file it uses the ID from the assets model. This is all well and good, however, I am having trouble getting the URL correct now. I created a route to my images:
resources :visual_submissions do
member do
get :images
end
end
And this is what my route looks like.
images_visual_submission GET /visual_submissions/:id/images(.:format) {:action=>"images", :controller=>"visual_submissions"}
Now the piece of code that in theory is supposed to access the image.
This is from my edit form. It is supposed to show the current images stored.
<%= f.fields_for :assets do |asset_fields| %>
<% unless asset_fields.object.new_record? %>
<p>
<%= asset_fields.object.image.url %>
</p>
<% end %>
<% end %>
Now this is obviously not going to work. I am not sure what object is doing here, but what I do know is, my images should be going through my visual_submissions controller which this is not touching. I am not entirely sure if I am asking this questions correctly, but I am stuck. One idea I had was to create a assets controller and move the images method into there but I am not sure how much that will help.
Any thoughts?
Thanks!
#Raymond, just put the last code snippet inside the _form.html.erb corresponding to your visual_submissions. Just be sure that you put it before the <%= f.submit %>, inside the form_for, of course. Hope that helps,

Resources