Paperclip functional test giving NoHandlerError [duplicate] - ruby-on-rails

Using Paperclip 3.0.1 in rails 3.2.2 I got this error:
**Paperclip::AdapterRegistry::NoHandlerError**
(No handler found for "2009-11-29-133527.jpg"):
In my model I have:
class Product < ActiveRecord::Base
...
has_many :assets
accepts_nested_attributes_for :assets
end
class Asset < ActiveRecord::Base
belongs_to :product
has_attached_file :image,
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename",
:styles => { :medium => "300x300>", :thumb => "100x100>" }
end
The exception is raised at:
def create
**#product = Product.new params[:product]**
...
end
with params:
{...,
"product"=>{"title"=>"wibble1",
**"assets_attributes"=>{"0"=>{"image"=>"2009-11-29-133527.jpg"}
},**
"description"=>"Who is wibble...",
"price"=>"23.45"
},
"commit"=>"Create Product",
...}
Anyone know what's going on?

This Error is raised because you aren't giving Paperclip a correct class. It's a just a String.
You should receive something like this in params
"asset"=>
{"image"=>
#<ActionDispatch::Http::UploadedFile:0x000000056679e8
#content_type="image/jpg",
#headers= "Content-Disposition: form-data; name=\"asset[image]\";
filename=\"2009-11-29-133527.jpg\"\r\nContent-Type: image/jpg\r\n",
#original_filename=""2009-11-29-133527.jpg"",
#tempfile=#<File:/tmp/RackMultipart20120619-1043-yvc9ox>>}
And you should have something like this in yout View (in HAML, very simplified):
= form_for #product, html: { multipart: true } do |f|
= f.fields_for :asset do |asset_form|
= asset_form.file_field :image
Remember to set your form to multipart: true.

I just ran into this problem myself. In my case it was caused by skipping the multipart form declaration in the markup.
I was using formtastic so I added this and got it working:
semantic_form_for #picture, :html => {:multipart => true} do |f|

Note there is a situation when working with an HTML5 canvas that is worth noting. Getting the canvas data as a DataURI string and sending that to server can cause this error. Canvas .toDataURL() will give something like "data:image/png;base64,iVBORw0KGg..." which you can send to server with other information, so its different than a standard multi-part form upload. On the server side if you just set this to the paperclip attachment field you will get this error. You need to conver it to a file or IO object. You could write a temp file like this:
data_uri = params[:canvasDataUri]
encoded_image = data_uri.split(",")[1]
decoded_image = Base64.decode64(encoded_image)
File.open("signature.png", "wb") { |f| f.write(decoded_image) }
or use Ruby's StringIO which acts like an in memory file interface
#docHolder.document = StringIO.new(decoded_image)
Hope this helps.

I had <input type="file" ... multiple="multiple"> on file input, so paperclip attachment data was in an array.
I solved this simply by removing multiple attribute on file input.

my problem was not accepting get method in routes so i changed it as patch method and it work fine.
<%= form_for #product, :url => "/products/#{#product.id}/upload",:method => :patch, :html => { :multipart => true } do |f| %>

I'm pretty sure your problem is with the form_for in the view,
try something like this:
<%= form_for #restaurante, :html => { :multipart => true } do |form| %>
Nome:<%= form.text_field :nome%>
Endereço:<%= form.text_field :endereco %>
Especialidade:<%= form.text_field :especialidade %>
Foto:<%= form.file_field :foto %>
<%= form.submit 'create'%>
<% end %>

In my case I was passing String, as in #MauricioPasquierJuan's answer, but I wasn't using a form so the rest of the answer doesn't apply.
I couldn't find any documentation of how to programatically update an attachment - what types can be assigned, and why assigning and saving the modified record does not save modified attachments. This question was the closest thing I found.
Inside a function that process files inside an uploaded zip file, after saving extracted files to temp files, this is my solution:
record.attachment = File.new( tempfile_path_as_string ) ## probably not the only option
record.attachment.save ## next line doesn't update attachment without this
record.save

Make sure you migrate the database after you install Paperclip ('rake db:migrate')... Also, you might need to add the new data fields generated by Paperclip to your 'attr_accessible' line in the model.
I had a similar problem when I was trying to get Paperclip workin on one of my projects.

I have met the same problem, I think it is because there are two tables sharing the same attached_file_name... In my case, I add a :photo column both to activities and tweets, then the case seems to be that the system can find one of them but not the other. Because the files are saved in /public/photo/:id/:id path, if you have two columns both named as photo, then the problem occurs I think.

for me the problem was like this:
I used such line in controller, as saw it in some answers:
#image = User.find(params[:id]).image.<b>path</b>(:small)
and I had the problem "no handler for the file"
so, I just removed "path" and it worked:
#image = User.find(params[:id]).image(:small)

When we upgraded from 4.2.x to 4.3.x, we had to change the main paperclip field attribute (picture, image, etc) from a relative URL to a full URL to eliminate this error.

Related

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,

ActiveAdmin, Formtastic, and Paperclip: Not Rendering File Dialog

I'm implementing a generic media gallery using Ruby on Rails. I've chosen ActiveAdmin to handle the administration portion of my task and it's worked well so far, except for one thing: It's not displaying the "Choose file" dialog as intended.
This is a form for my "Media" section of ActiveAdmin. I have a model called "Medium" with the following fields (in addition to id and timestamp:
asset_file_name
asset_file_size
asset_content_type
asset_updated_at
My Medium model looks like this:
class Medium < ActiveRecord::Base
has_and_belongs_to_many :galleries
has_and_belongs_to_many :entities
has_attached_file :asset, :styles => { :medium => "300x300>", :thumb => "100x100>" }
attr_accessible :asset
end
And I'm adding it to the ActiveAdmin form like this:
form :html => { :enctype => "multipart/form-data" } do |f|
f.input :asset, :as => :file
f.buttons
end
Here's a screencap of my ActiveAdmin page:
I see nothing wrong with how I'm implementing this. I've read that Formtastic has historically had issues with paperclip and I'm not averse to switching to attachment_fu or any other suitable solutions.
I should also note: I know that I can add in a custom partial. It's not my ideal solution, as I'd like to keep everything in the Formtastic DSL.
Thanks!
Formtastic requires that you wrap all calls to #input in a call to #inputs. It's definitely something that I would like to see fixed in Active Admin.
It should work if you wrap your input in a call to inputs:
form :html => { :enctype => "multipart/form-data" } do |f|
f.inputs do
f.input :asset, :as => :file
end
f.buttons
end
Let me know if this works for you.
Or you can do:
form :html => {:multipart => true} do |f|
which is easier to remember, imho.
the latest active admin handle it automatic
I use carrier wave with active admin and works as above.

Image file input with Formtastic and ActiveAdmin

I started to use formstatic but I need to make a file field with image preview. I mean, when i edit an object, i want to see the image already linked.
How can I do that?
Thank you !
The answer is to use the hint attribute :
ActiveAdmin.register Event do
form :html => { :enctype => "multipart/form-data" } do |f|
f.input :map, :as => :file, :hint => f.template.image_tag(f.object.map.url(:thumb))
end
end
Bye
Use paperclip with formtastic
Formtasitc's github page mentions that it supports paperclip:
:file – a file field. Default for file-attachment attributes matching: paperclip or attachment_fu.
Here are some useful screencasts that will get you going:
Paperclip
Cropping images
EDIT:
To display an image in a column of a grid in ActiveAdmin you need to make a custom column (This is untested and could be flawed, I'm extrapolating this from the documentation):
index do
column "Title" do |post|
link_to image_tag("path to file", :alt => "post image"), admin_post_path(post)
end
end
Two Gems and one plugin can help your case:
Make sure you look at:
Gems:
Paperclip: https://github.com/thoughtbot/paperclip
RailsCast on PaperClip: http://railscasts.com/episodes/134-paperclip
CarrierWave: https://github.com/carrierwaveuploader/carrierwave
RailsCast on CarrierWave: http://railscasts.com/episodes/253-carrierwave-file-uploads
Jquery File Upload: https://github.com/blueimp/jQuery-File-Upload
Jquery File Upload RailsCast: http://railscasts.com/episodes/381-jquery-file-upload (Need a Pro Account for RailsCast)
As #ianpetzer said, in Rails 4.2 / ActiveAdmin master the current answer causes an object reference to be written out as well. The correct answer for 2016 should be similar to this answer:
form :html => { :multipart => true } do |f|
f.inputs do
#...
f.input :image, required: false, hint: image_tag(object.image.url(:medium)).html_safe
#...
end
end

Generating unique HTML ids in Rails when using a repeated partial that has form_for

I have a view on my current project which does something like the following(in haml):
-#horses.each do |horse|
= render :partial => 'main/votingbox', :locals => {:horse => horse}
The in the _votingbox.html.haml file I have the following:
%div.votingbox
%span.name= horse.name
%div.genders
- if horse.male
%img{:src => 'images/male.png', :alt => 'Male'}
- if horse.female
%img{:src => 'images/female.png', :alt => 'Female'}
%div.voting_form
= form_for(Vote.new, {:url => horse_vote_path(horse)}) do |f|
= f.label :comment, "Your opinion"
= f.text_field :comment
...
a bunch of labels and input elements follow generated using the form helpers
This will generate working code but it does generate forms with the same ids for all the form elements which makes the HTML invalid once the votingbox partial is rendered a second time.
My first guess at fixing this was to specify a unique :id to form_for but that only applies to the form tag generated by form_for and not any of the tags inside the form_for block.
One definite solution to this problem is to go through and manually define my own unique ids on form_for and all the form elements I use. This is more work than I had hoped for.
Is there an easier or cleaner way to get unique ids in a similar format to the way Rails currently generates them on all my form elements?
I have removed the original answer as it is totally irrelevant to the updated version of the question.
Update: So now we know that you have an unsaved ActiveRecord object passed to the form_for call, the answer becomes simple: You can override any parameter that form_for generates. That includes the element id. And fields_for sets the context for a specific record.
= form_for(Vote.new, :url => horse_vote_path(horse), :id => dom_id(horse, 'vote')) do |f|
= f.fields_for horse, :index => horse do |fh|
= fh.text_field :whatever
…
You can override the autogenerated ids and names of all form_for content with :as like the following:
= form_for(Vote.new, :as => horse.name, {:url => horse_vote_path(horse)}) do |f|
= f.label :comment, "Your opinion"
= f.text_field :comment
So if a given horse.name is foobar, it will generate a comment field whose id is foobar_comment and name is foobar[comment]
But remember to make sure that the dynamic parameter is acceptable as an html id, a horse.name like hor$e is not acceptable as an html id and therefore might break something.
P.S: Sorry for answering very late, but at the time the question was asked, I haven't had learnt anything at all about rails! hope that might help someone out there!

Ruby on Rails: form_for works, but remote_form_for doesn't

<% remote_form_for(#media, :url => url_for(:controller => :attachments,
:action => :add_from_disk, :object_id => #object),
:html => { :multipart => true, :id => 'new_media', :onsubmit=>'unsaved_changes = false' } ) do |f| %>
but if I change the remote_form_for to form_for, I don't get this error:
ActiveRecord::RecordInvalid (Validation failed: Document file name must be set.):
Why would it work with form_for, but not the AJAX version?
You can't upload a file using AJAX.... You'll need to implement a flash uploader to send files in the background. It's not pretty, but Uploadify is pretty cool
Recommend keeping file uploading as regular form for.
Or you can use the jQuery form plugin, which works great. In this case you'd do a normal form_for, and inside of your javascript file (once you've included jquery and the jQForm lib in your html) you'd do something like this:
$(function() {
$("#myFormDomID").ajaxForm({ iFrame : true });
});

Resources