I have set up Paperclip and ImageMagick successfully on my system, and files are uploading correctly, being resized, and and being saved into the right folders.
I try to display those images in my view:
<%= image_tag #customer.logo.url(:medium) %>
No image is displayed. When I go to the image's direct url I get:
Routing Error
No route matches "/images/assets/logos/1/medium/corplogo.jpg" with {:method=>:get}
This is a local server still in development and running on Windows. My forms are multipart:
<% form_for #customer, :url => {:action => "update", :id => #customer}, :html => {:multipart => true, :id => "myform"} do |f| %>
------ Dev Server ------
Processing ApplicationController#index (for 127.0.0.1 at 2010-09-27 04:38:33) [G
ET]
Parameters: {"1285570273"=>nil}
ActionController::RoutingError (No route matches "/images/assets/logos/1/medium/corplogo.jpg" with {:method=>:get}):
haml (3.0.15) rails/./lib/sass/plugin/rack.rb:41:in `call'
Rendering rescues/layout (not_found)
------ Model ------
has_attached_file :logo,
:url => "assets/logos/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/logos/:id/:style/:basename.:extension",
:styles => {:medium => "300x300>", :thumb => "100x100>" }
I found the answer to the problem, and it lies with the url declaration in the model.
Instead of:
:url => "assets/logos/:id/:style/:basename.:extension"
it should be:
:url => "/assets/logos/:id/:style/:basename.:extension"
I got this error using the "webrick" server. and I check all the file access permission on my "public/system" folder, they are normal.
finally I switched to apache/passenger, it works, the images are displayed correctly.
Related
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.
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!
I am using paperclip for image upload:
I am getting the error:
Started GET "/assets/audios/thumbnails/7/thumb/4_X_4.jpg?1345530644"
for 127.0.0.1 at 2012-08-21 12:03:04 +0530
Served asset /audios/thumbnails/7/thumb/4_X_4.jpg - 404 Not Found (1ms)<br/>
ActionController::RoutingError (No route matches [GET] "/assets/audios/thumbnails/7/thumb/4_X_4.jpg"):<br/>
In my model as:
has_attached_file :thumbnail,
:styles => {:medium => "300x300>", :thumb => "100x100>"},
:url => "assets/:class/:attachment/:id/:style/:basename.:extension",
:path => ":rails_root/assets/:class/:attachment/:id/:style/:basename.:extension"
This
:url => "assets/...",
:path => ":rails_root/assets/..."
should be
:url => "/assets/...",
:path => ":rails_root/public/assets/..."
Although it's a terrible idea to save attachments in the assets dir. You can have another, like files inside public:
:url => "/files/:class/:attachment/:id/:style/:basename.:extension",
:path => ":rails_root/public/files/:class/:attachment/:id/:style/:basename.:extension"
Saving inside public/files and using /files url will make the webserver hit the files before rails (of course, correctly configuring your web server, e.g. nginx, is another issue)
I found the correct solution after searching on web continuously. I tried to handle this problem by all probabilities which I could think of like:- permissions, correcting paths,changing server from webrick to thin. Then I studied about the environments properties.
So, here is the correct answer inside your Production environment set:
config.serve_static_assets = true
This solved the problem.
Following link may help you:Upload image using paperclip
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..............
For reasons beyond this problem, I need to respond with JSON when creating an image:
<%=
raw({
...
:url => #image.url(:width => #width, :height => #height),
:edit_link => render({:state => :image_edit_table_cell, :template_format => :html}, #image),
# btw, I've also tried passing :format => :html
:delete_link => link_to_destroy_image(#image, :remote => true, :path => url_for_event(:destroy, :image_id => #image)),
...
}.to_json)
%>
However, in that JSON, I want to include some pretty fancy HTML. To include that, I render a state/view (as you can see in the :edit_link portion). This is the image_edit_table_cell.html.haml view of the widget:
= link_to_edit_image #image, :remote => true
# ... doesn't really matter - as long as you know this is html.haml
However, when I create an image, and the JSON is rendered, I get a Missing template error:
ActionView::Template::Error (Missing template cell/rails/image_edit_table_cell with {:handlers=>[:builder, :rjs, :rhtml, :erb, :haml, :rxml], :locale=>[:en, :en], :formats=>[:json]} in view paths "/home/ramon/source/unstilted/app/widgets", "/home/ramon/source/unstilted/app/widgets/layouts" and possible paths image/table/image_edit_table_cellapplication/image_edit_table_cellapotomo/widget/image_edit_table_cellcell/rails/image_edit_table_cell):
6: :caption => #image.caption || "",
7: :text_tag => #image.text_tag(:width => #width, :height => #height),
8: :url => #image.url(:width => #width, :height => #height),
9: :edit_link => render({:state => :image_edit_table_cell, :template_format => :html}, #image),
10: :delete_link => link_to_destroy_image(#image, :remote => true, :path => url_for_event(:destroy, :image_id => #image)),
11: :success => true
12: }.to_json)
app/widgets/image/table_widget.rb:37:in `image_edit_table_cell'
app/widgets/image/table/new_image.json.erb:9:in `_app_widgets_image_table_new_image_json_erb___457172591_99648970_0'
app/widgets/image/table_widget.rb:16:in `add_image'
app/widgets/image/uploader_widget.rb:22:in `upload'
It seems like the problem is that since I'm rendering it from a JSON file, it doesn't know to look for an HTML file (thus the format it's looking for is json. That's why you see the :template_file => :html option (I got that from here) in the first block of code above.
I'm using these gems:
'rails', '3.0.10'
'cells', '3.6.2'
'apotomo', "1.1.2"
Apparently, this is a Rails issue, not an Apotomo issue. This answer did it for me! Key is setting the format in your view file before you render your html view:
<% self.formats = ["html"] %>