Rails paperclip not showing image - ruby-on-rails

I am new to paperclip, and I wanted to see how it would work. I generated a simple model Monkey and got the following:
rails g scaffold monkey description age:datetime
rails g paperclip monkey facepic
rake db:migrate
Model
class Monkey< ActiveRecord::Base
has_attached_file :facepic, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
View new/edit
<%= form_for #monkey, :url => monkies_path, :html => { :multipart => true } do |f| %>
...
<div class="field">
<%= f.label :facepic %><br>
<%= f.file_field :facepic %>
</div>
View show
<%= image_tag #monkey.facepic.url %>
Controller
#monkey = Monkey.new(monkey_params)
I can create new monkeys, but the show view doesn't seem to find the uploaded file. I have no error messages, except a routing error to 'missing.png'. There is no trace to the uploaded image. I am using Rails 4.1.6. What am I missing here? How do I troubleshoot this thing? The gem is installed and also imagemagick is installed.
This is what the logs say:
ActionController::RoutingError (No route matches [GET] "/facepics/original/missing.png"):
...
Started GET "/monkies/new" for 127.0.0.1 at 2014-09-19 14:40:22 +0200
Processing by MonkiesController#new as HTML
Rendered monkies/_form.html.erb (4.0ms)
Rendered monkies/new.html.erb within layouts/application (5.0ms)
Completed 500 Internal Server Error in 12ms
ActionView::Template::Error (No route matches {:action=>"show", :controller=>"monkies"} missing required keys: [:id]):
There is no error message displayed however when I create a new monkey... :'(
EDIT:
The Monkey model is created, but the paperclip columns remain empty.

This error clearly show that your images are not getting saved because path and url not specified in your has_attached_file block. It should be like :
has_attached_file :facepic,
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename",
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "path to default image"
here default_url show image that you want if no image uploaded. For more detail you can go here http://rdoc.info/gems/paperclip/4.2.0/Paperclip/ClassMethods%3ahas_attached_file .
And for other error you can follow this link Paperclip::Errors::MissingRequiredValidatorError with Rails 4

Starting with Paperclip version 4.0, all attachments are required to include a content_type validation, a file_name validation, or to explicitly state that they're not going to have either.
Paperclip raises Paperclip::Errors::MissingRequiredValidatorError error if you do not do any of this.
In your case, you can add any of the following line to your Post model, after specifying has_attached_file :image
Option 1: Validate content type
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
-OR- another way
validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
-OR- yet another way
is to use regex for validating content type.
Option 2: Validate filename
validates_attachment_file_name :avatar, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]
Option 3: Do not validate
If for some crazy reason (can be valid but I cannot think of one right now), you do not wish to add any content_type validation and allow people to spoof Content-Types and receive data you weren't expecting onto your server then add the following:
do_not_validate_attachment_file_type :image
Note:
Specify the MIME types as per your requirement within content_type/ matches options above. I have just given a few image MIME types for you to start with.
Reference:
Refer to Paperclip: Security Validations, if you still need to verify. :)
For details you can go to This question

I am sorry to say that my problem eventually was a bunch of things:
Had to add :facepic to the strong params
Had to add validations of content type to the model
Paperclip has a dependency... the file-command, which isn't shipped on Windows.
which can be downloaded here: http://sourceforge.net/projects/gnuwin32/?source=typ_redirect
After all three, it works like a charm!
Thank you all!

Related

Adding Paperclip Attachment to Spree Orders Table,

I am working on an ecommerce website using Solidus, Rails. The site allows you to order photo frames & prints from a variety of options.
To print a photo a user must upload the jpg file of the photo. So, to allow that I modified the orders table and added a paperclip attachment called 'attachment'
I ran the following command
rails generate paperclip SpreeOrder attachment
Which generated the migrations, then I ran rake db:migrate
Then I created a spree/order_decorator.rb file, and added has_attached_file
module Spree::OrderDecorator
has_attached_file :attachment, styles: {
:medium => {
:geometry => "640x480",
:format => 'jpeg'
},
:thumb => { :geometry => "160x120", :format => 'jpeg', :time => 10}
}, :processors => [:transcoder]
validates_attachment_content_type :attachment, content_type: /\Aimage\/.*\z/
Spree::Order.prepend self
end
After this I ran the server, and ended up getting this error
undefined method `has_attached_file' for Spree::OrderDecorator:Module (NoMethodError)
I have configured solidus for use with paperclip only, so I am really confused as to why I am getting this error, even later I manually went and generated a paperclip.rb file in the config/initializers directory, but still I get the same error.
Please help with this!!
Thank You!!
You should add those paperclip method at class level in the prepended module:
def self.prepended(base)
base.has_attached_file
end

How does lambda function works in rails with an example from paperclip gem

I had a problem with the Paperclip gem where the default_url doesn't load after it fingerprinted in production environment, my code was like this:
class User
# Attachments to Paperclip - Profile pic
has_attached_file :profilepic_attachment,
:styles => {
thumb: '100x100#',
square: '500x500#'
},
:default_url => ActionController::Base.helpers.asset_path("missing/default_user.png"),
:preserve_files => true
validates_attachment_content_type :profilepic_attachment, content_type: /\Aimage\/.*\Z/
end
Note that when I do rails c in production and print out ActionController::Base.helpers.asset_path("missing/default_user.png"). The fingerprinted version (correct version) is printed out.
default_user-fb34158daae99f297ad672c43bb1a4d3917d8e272b5f2254aa055392aa2faa94.png.
However, when I inspect it from browser, the original /assets/missing/default_user.png appeared.
I struggled for long time until I came across this post, which tells me to change
:default_url => ActionController::Base.helpers.asset_path("missing/default_user.png"),
to
:default_url => lambda { |image| ActionController::Base.helpers.asset_path("missing/default_user.png") },
I wasn't sure what happened, but then it works. I then wonder what lambda function is for and when is it used in rails? also, it passed in a variable |image| but seems it wasn't use in the code. Why is that?
Thanks!

Paperclip attachment saving with incorrect S3 URL about 50% of the time

Update:
So this is definitely related to the :hash_data option, specifically the :updated_at segment. Somehow the files are being saved to the S3 bucket with a different :updated_at value than Paperclip uses to read the file. Could this be due to some race condition, considering that it occurs intermittently? As I mentioned below, this issue began after upgrading Paperclip to 4.2.1.
I will greatly appreciate any thoughts/tips you guys have on this. Thank you!
When uploading images via Paperclip to S3 bucket, it sometimes saves the files with a different filename than that returned by the attachment#url method. For example, an image is saved to
main_event_photos_46_47fd4f3c2fea17fbb7a0bd27c648911557f9e12b_main.png
However calling #event.main_event_photo.url(:main) returns
main_event_photos_46_15744de74a36207b672356b5ad4c6b30eb4ba85f_main.png
So as you can see, the :hash section of the interpolation does not match, and I have no way of finding the actual url besides opening the bucket in the S3 console. This issue seems to occur about half the time. Sometimes uploading the exact same file does save properly, and the url method accesses it correctly.
This issue began occurring after we upgraded Rails/Ruby/Paperclip. We're now using:
Ruby 2.1.5
Rails 4.2.0
Paperclip 4.2.1
Note that on development, files always save correctly (local filesystem). I have scoured Stackoverflow and Google to no avail. Please let me know if I can provide any additional information. Thank you!
EDIT:
Model:
has_attached_file :main_event_photo, {
:styles => { :original => {:geometry => "1280x800#", :format => 'png'},
:main => {:geometry => "640x400#", :format => 'png'},
:thumb => {:geometry => "330x220#", :format => 'png'}
},
:convert_options => {:original => '-quality 80',
:main => '-quality 80',
:thumb => '-quality 80'
},
:default_style => :main
}.merge!(PAPERCLIP_STORAGE_OPTIONS) # this is defined in the config/environments
validates_attachment_content_type :main_event_photo, :content_type => ['image/jpeg', 'image/png', 'image/gif', 'image/x-png', 'image/pjpeg']
validates_attachment_presence :main_event_photo
Form (basically):
<%= simple_form_for(#event, :url => { :action => #event.id.nil? ? "create" : "update" }) do |f| %>
<%= f.file_field :main_event_photo %>
<% end %>
Note we have many models with Paperclip attachments, and the issue occurs on each.
So this turned out to be the result of a bug. I upgraded Rails to 4.2.1.rc1 which was released last week, and the issue was resolved. If anyone wants more information, check out the thread on Github: https://github.com/thoughtbot/paperclip/issues/1772. It includes a workaround for those who can't upgrade Rails.

Getting Image Paperclip::Errors::NotIdentifiedByImageMagickError after updating to Paperclip 3.4.0

I got the following message after upgrading:
Paperclip 3.0 introduces a non-backward compatible change in your
attachment path. This will help to prevent attachment name clashes
when you have multiple attachments with the same name. If you didn't
alter your attachment's path and are using Paperclip's default, you'll
have to add :path and :url to your has_attached_file definition.
For example:
has_attached_file :avatar,
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename"
So I did so:
post.rb:
has_attached_file :image, :styles => { :medium => "170x300>",
:thumb => "142x185>" },
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename"
But then I saw this error message:
Image Paperclip::Errors::NotIdentifiedByImageMagickError
I even added this to environments/development.rb:
Paperclip.options[:command_path] = "/usr/bin/"
(which identify outputs /usr/bin/identify)
But still no luck.
What could be the problem?
Wow, I didn't expect this. The problem wasn't due to upgrading.
It was because the file I was uploading was named like this:
Screenshot at 2012-11-26 16:22:44.png
Weird.
The issue is in the filename.
colons are not accepted, if you remove the colon from the attachment name using gsub it'll be accepted always.

How to specify :path and :url to save img in Paperclip, Rails 3.0.12

I'm using Paperclip with my Rails 3.0 app in order to add an avatar to a user, and it won't save the image because the paths are off. Heres what I get:
Started GET "/profilepics/small/missing.png" for 127.0.0.1 at 2012-04-11 23:38:29 -0700
ActionController::RoutingError (No route matches "/profilepics/small/missing.png"):
My user model has:
has_attached_file :profilepic, :styles => { :small => "150x150>" }
What should I put for :path => & :url => ?
Form looks like :
<% form_for #user, :html => { :multipart => true } do |f| %>
<%= f.file_field :profilepic %>
<% end %>
Logs look like :
Started GET "/system/profilepics/small/missing.png" for 127.0.0.1 at 2012-04-12 00:33:51 -0700
ActionController::RoutingError (No route matches "/system/profilepics/small/missing.png"):
Rendered /usr/lib/ruby/gems/1.9.1/gems/actionpack-3.0.12/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (1.2ms)
See my sample:
has_attached_file :avatar, :styles => { :thumb => "50x50#", :large => "1000x1000>", :medium => "200x200#" },
:default_url => "/system/avatars/:style/missing.png",
:url => "/system/:attachment/:id/:style_:filename",
:path => ":rails_root/public/system/:attachment/:id/:style_:filename"
:default_url - is the path for the default image, when the user didn't upload any avatar
"#" - this symbol is to crop image
then you can show your images as such:
<%=image_tag(#user.avatar.url(:thumb))%>
<%=image_tag(#user.avatar.url(:medium))%>
Works now!!!
For people struggling with the same issue, here's a few important things to ALWAYS make sure and check:
In your form, always specify { :multipart => true } otherwise, the form won't accept file attachments.
<%= form_for #user, :html => **{ :multipart => true }** do |f| %>
In your user.rb (or whatever model you want to add attachments to ), make attr_accessible :photo (or whatever you name your attachment)
ALWAYS restart your server after installing a new Gem.
:) Thanks guys!!!!
There is no need to given url and path option if you simply want to display an image.
Use this line in show page and it will display image...
<%=image_tag(#user.profilepic.url(:small))%>
And enjoy..............

Resources