Retrieve file from S3. - Carrierwave Rails Gem - ruby-on-rails

I'm implementing Carrierwave with fog storage into my Rails App. The whole purpose of this app is to store pdf articles and have the ability for anyone with access to the app to retrieve them. Right now, I have the functionality of storing the article pdf working great. But, now I need to be able to retrieve the pdf from S3. Is this possible? I noticed in the docs there is a uploader.retrieve_from_store!("my_file.png") method. I tried to run this in the console and I got this error NoMethodError: undefined method retrieve_from_store! for ArticleUploader:Class Any help with this would be great! I'm just not finding any suitable answers so far. Thanks!
Article Uploader
class ArticleUploader < CarrierWave::Uploader::Base
storage :fog
def extension_whitelist
%w(jpg jpeg gif png pdf)
end
end
Article Model
class Article < ApplicationRecord
mount_uploader :file, ArticleUploader
validates :title, presence: :true
validates :publication_date, presence: :true
validates :source, presence: :true
end

You can access it with the methods that carrierwave has, in your case:
article = Article.find(1)
article.file.url
If you are on development it will output the path for the file and if you are on production and using S3, it will output the whole url, http://s3.amazonaws.com/<vendor>/articles/1/file.pdf for example.
You can find more information on the official docs:
https://github.com/carrierwaveuploader/carrierwave#activerecord
There is also an old rails cast on that http://railscasts.com/episodes/253-carrierwave-file-uploads

Related

Report from backend to upload to s3 using carrierwave gem ruby

I have Axlsx::Package.new object which is used to create a excel file in backend and now i have to upload this excel file to s3 using carrierwave gem. I have either file path or Axlsx::Package.new object but in both case it is throwing file can't be blank.. I am not sure what I am doing wrong.
Please help me how can I achieve this.
class Attachment < ApplicationRecord
# CarrierWave
mount_uploader :file, AttachmentUploader
validates :file, presence: true
end
when I execute this line, where I don't have ActionDispath::FileUpload object as i am creating file in backend not from UI form. due to this I have
file = Axlsx::Package.new
file_path = "uploads/exports/download_request_#{current_datetime}.xlsx"
attachment = Attachment.create!(file: file, entity_type: self.class)
i tried with file also and file_path also but it is not working and throwing file can't be blank...
class Attachment < ApplicationRecord
# CarrierWave
mount_uploader :file, AttachmentUploader
validates :file, presence: true
end
it should save to s3 as how it is working in case when i upload file from UI form using input type file tag.
Please help

Can't upload image with Paperclip in Ruby on Rails

I'm working on a simple api using ruby on rails, and tried to attach an image to my post but I always get this error:
"[paperclip] Link failed with File exists # syserr_fail2_in -
C:/Users/Safouene/AppData/Local/Temp/d5e01d9478f9774f9f669fd29da0cb2720190401-5260-1tjlj3v.png;
copying link
C:/Users/Safouene/AppData/Local/Temp/d5e01d9478f9774f9f669fd29da0cb2720190401-5260-ooex8h.png
to
C:/Users/Safouene/AppData/Local/Temp/d5e01d9478f9774f9f669fd29da0cb2720190401-5260-1tjlj3v.png
Command :: file -b --mime
"C:/Users/Safouene/AppData/Local/Temp/d5e01d9478f9774f9f669fd29da0cb2720190401-5260-1tjlj3v.png""
Completed 204 No Content in 65ms (ActiveRecord: 1.0ms)
Here is My Model :
class Action < ApplicationRecord
belongs_to :user
validates :title ,presence: true
validates :desc ,presence: true
validates :location , presence: true
has_attached_file :picture
validates_attachment :picture, presence: true
do_not_validate_attachment_file_type :picture
end
This is not strictly answering your question but I feel I should point out that since the release of active storage with rails 5.2 many of these file upload gems have been deprecated. This means they will no longer be maintained. (see github page https://github.com/thoughtbot/paperclip)
With that in mind I would strongly advise you to use active storage, rather than paperclip.
Active storage is part of the rails core framework now so you can rest assured it will be maintained and always work the the latest releases of rails.
Plus, active storage is super easy to implement and full of really cool features.
You can read more about active storage here: https://edgeguides.rubyonrails.org/active_storage_overview.html

Carrierwave remote attachment url not working on creation

I have the following model called ApplicationAttachment in my Ruby on Rails project.
I also have uploaded files on my s3 bucket. When i try to upload the image to my model, i dont get an error but attachment is nil and the remote_attachment_url is not saving the file. Not sure what is the problem.
My code is this
ApplicationAttachment.create!(remote_attachment_url: "http://www.jqueryscript.net/images/jQuery-Plugin-For-Fullscreen-Image-Viewer-Chroma-Gallery.jpg")
This doesnt return any error but it doesnt save the image.
class ApplicationAttachment < ActiveRecord::Base
mount_uploader :attachment, DeveloperReferralAttachmentUploader
attr_accessible :id, :attachment, :remote_attachment_url, :created_at, :updated_at
end
class DeveloperReferralAttachmentUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(pdf jpg jpeg gif png)
end
end
How do i ensure that the remote_image_url saves when created via Carrierwave.
Thanks
I think you might want to explicitly save the attachment instead of using create.
aa = ApplicationAttachment.new(
remote_attachment_url: "http://www.jqueryscript.net/images/jQuery-Plugin-For-Fullscreen-Image-Viewer-Chroma-Gallery.jpg"
)
aa.save

rails admin + carrierwave updating breaks the image url

I'm using Rails 5 with rails_admin and carrierwave gems.
I have a model Photo and and image uploader mounted on it (as per carrierwave documentation), looks roughly like this:
class Photo < ActiveRecord::Base
mount_uploader :image, ImageUploader
belongs_to :project
validates :name, presence: true
validates :image, presence: true
end
Given I have already some Photo objects created I can see a list of them in the rails_admin admin view.
And I start editing one of them
And I edit name
And I proceed to save it
Then rails admin fires some of it's magic and photo is being saved but after this action the image dissapears.
I have been digging a little in what request are being fired and rails_admin fires a PUT request with such params:
{
"authenticity_token"=>"xxx",
"photo"=>{
"name"=>"test2",
"description"=>"ewdeeweeefxxxwefwe",
"project_id"=>"3",
"image_cache"=>"",
"main"=>"0",
"about_us"=>"0"
},
"return_to"=>"http://localhost:3000/panel-admin/photo?model_name=photo", "_save"=>"", "model_name"=>"photo", "id"=>"29"}
and my Photo object is being update with not only name but also with image_url that of course overrides Image that already was mounted to the Photo
I have no idea why this is happening and how to prevent it.
Anyone might have encountered this issue and knows how to resolve it?
I found that. When I uncomment my custom filename method in uploader, it works well.

Test failing for uploading documents fails in rails

I am trying to test for uploading documents in rails. I am using carrierwave to upload documents. The relevant code is given below.
Document Model Test Code
class DocumentTest < ActiveSupport::TestCase
def setup
#category = categories(:category_a)
#document = #category.documents.build(file_name: "abc", file: "abc.doc")
end
test "document valid" do
assert #document.valid?
end
Document Model Code
class Document < ActiveRecord::Base
belongs_to :category
mount_uploader :file, FileUploader
validates :file_name, presence: true
validates :file, presence: true
validate :file_size
end
file_uploader code
The following are the files I have whitelisted.
def extension_white_list
%w(pdf doc htm html docx xlsx xml)
end
I get a Failed assertion when I run the tests. I commented out the validates :file, presence: true code and the tests pass. I have file as type string in the database. However, passing in a string value is the same as passing a blank value. Therefore, the presence: true validation fails. I am not sure why that is failing even though I am passing in a string value. I think I need to pass in additional params or information for the tests to know what kind of file it is. Thanks!
This is not how you pass a file to the carrierwave model. Have a look at these examples:
https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Use-test-factories
Also, carrierwave has its own validators you might want to use:
https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Validate-uploads-with-Active-Record

Resources