Paperclip failing to upload on specific scaffold, yet works on others - ruby-on-rails

I know there are tons of questions about paperclip, but I failed to find the answer to my problem.
I know its prob just something simple, but I I'm running out of hair to pull out.
I have paperclip working on other parts of my project, they work with no problem, however, a certain scaffold fails to upload, all the attributes to the uploaded file are nil.
Here are the relevant information.
Model:
has_attached_file :foo,
:styles => { :thumb => "140x140>" },
:url => "/data/:id/:style/:basename.:extension",
:path => ":rails_root/public/data/:id/:style/:basename.:extension"
View:
<% form_for(#bar, :html => { :multipart => true }) do |f| %>
<%= f.error_messages %>
----------
<li><%= f.label :top %>
<%= f.file_field :foo %></li>
----------
<ul><%= f.submit "Save" %></ul>
<% end %>
Also, comparing the logs to the parts that work, the :foo attribute seems to be passing different values than in the ones that work.
In the logs, when the paperclip function works, it looks like this
"image"=>#<File:/var/folders/M5/M5HEb+WhFxmqNDGH5s-pNE+++TI/-Tmp-/RackMultipart20100512-1302-5e2e6e-0>
when it does not, it seems to pass the file name directly
"foo"=>"foo_image.png"
I am developing locally on MacOSX using local rails and ruby libs.

Still haven't narrowed it down, but just to let people know, the problems went away after erasing all the views and regenerating them from scratch, meaning it was a view issue.
Will follow up.

Related

Uploading 2 images in rails using two field

I have a form for a blog, and I would like to have two field for images. One image being the cover (in Show) and another image will serve as a preview (in index).
My form looks as follow:
<%= semantic_form_for #blog, :html => { :multipart => true } do |f| %>
<%= t :Choose_File_for_cover %> <%= f.file_field :image_path, id: "avatar-upload2", required: true %>
<img id="img_prev3" width="100%" height=200 src="#" alt="your image" class="img-thumbnail hidden"/>
<%= t :Choose_File_for_homepage %> <%= f.file_field :homepagepic, id: "avatar-upload3", required: true %>
<%= f.hidden_field :image_path_cache %>
<%= f.hidden_field :homepagepic_cache %>
<%= f.actions do %>
<%= f.action :submit, :as => :input %>
<% end %>
<% end %>
My model looks like:
class Blog < ApplicationRecord
belongs_to :user
acts_as_taggable
mount_uploader :image_path, BlogUploader
mount_uploader :homepagepic, BlogcoverUploader
end
It works well when I only have the image_path (the cover), but when I add a new field for homepagepic, i get a ROLLBACK at validation.
Can someone help me on how to select files through two separate fields on the same form please.
Thank you
The code you've provided is very sparse and it would be helpful to see a little bit more (e.g. the controller and the uploader).
I can, however, hazard a guess: image_path is an existing helper method provided by Rails (see https://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-image_path). I have absolutely no idea what happens when you use this as a name for a form field. It could also be because you declare your submit button to be an input (I've only ever seen and used as: :button for f.action :submit).
So overall, I would pick the following approach:
rename your upload fields to cover_image and the other one to preview_image (that's what you've described in your posts as their respective purpose, so you should name them accordingly)
change the submit to a button and remove all the noise from your template and start with the bare minimum: the two upload fields and nothing else (see sample code below – note that I haven't tested it but it should work or be very close to working)
after that works, start adding back the noise (i.e. the translations, the cache fields etc.)
Test that it still works after every step. If you can write a Capybara test, do that – otherwise test it manually.
If you have questions, feel free to ask.
<%= semantic_form_for #blog, html: { multipart: true } do |f| %>
<%= f.file_field :cover_image %>
<%= f.file_field :preview_image %>
<%= f.actions do %>
<%= f.action :submit, as: :button %>
<% end %>
<% end %>
class Blog < ApplicationRecord
belongs_to :user
acts_as_taggable
mount_uploader :preview_image, BlogUploader
mount_uploader :cover_image, BlogcoverUploader
end
As the previous poster said it's hard to debug your code without all the pieces to the puzzle. A ROLLBACK is happening because one or more validations failed.
Any time you have a ROLLBACK you can add a ! to the create or update method being called on the object being rolled back and ActiveRecord will throw an error telling you why the ROLLBACK happened instead of failing gracefully.
Once you know why your object isn't persisting you can check the params of the controller action that form is submitting to. Perhaps you forgot to whitelist a param via strong params?

Is it correct to specify ":html => { :multipart => true}" for form_for?

We're running Rails 3.2.19 and Ruby 2.1.2.
We have a legacy line of code (actually, more than one, but this line is of particular concern) that reads
form_for [#commentable, #comment], :html => { :multipart => true, :class => "lightbox_form"} do |f|
The form data may or may not include an uploaded file at the user's discretion.
Many examples in SO refer to specifying the :multipart setting, but then I see this answer at Form_for with :multipart => true spits out and then in looking at the docs at http://guides.rubyonrails.org/v3.2.19/form_helpers.html#uploading-files, I see that it shouldn't be necessary (except if using form_tag). I also see this discussion at https://github.com/rails/rails/issues/10176 that adds to my confusion.
I'm asking in part because we're getting EOF errors in Rack (no content coming through on the multipart parser; see Rack throwing EOFError (bad content body) if you're interested in those details).
Our code may have been previously run under earlier versions of Rails when it may have been necessary (and so may just be a holdover). But given all the other examples on SO that include :multipart, I want to better understand if or when :multipart is needed with form_for before I remove it and what side effects I may encounter.
It's not required in Rails 3.1 and later, as long as you're using form_for with file_field like this:
<%= form_for #person do |f| %>
<%= f.file_field :picture %>
<% end %>
This will not work:
<%= form_for #person do |f| %>
<%= file_field_tag 'person[picture]' %>
<% end %>
You can easily verify that it's working. Inspect the generated HTML and look for the enctype="multipart/form-data" attribute on the form tag. Rails doesn't do any magic beyond setting the encoding type, so if the attribute is there, you're good.

File uploading Mailboxer Gem

I'm trying to send a message with an attachment in Mailboxer Gem.
My stack is : Rails 4 and Ruby 2.1.1
However, I can see that attachment using CarrierWave is already supported as the link in the code below.
https://github.com/ging/mailboxer/blob/4b2681c1790b823f7b493fb00b41e9899bb90ebe/app/models/message.rb#L13
However, I did my setup exactly like that. Normal message without an attachment is going fine.
This is my code :
Controller :
def create_message
if params[:user].present? & params[:message].present? & params[:subject].present?
current_user.send_message(User.find(params[:user]), params[:message], params[:subject])
redirect_to inbox_path
end
end
This is my view code :
<%= form_tag do %>
<%= select_tag 'user', options_from_collection_for_select(User.all, :id, :fullname) %><br/>
<%= text_field_tag 'subject' %><br/>
<%= text_area_tag 'message' %><br/>
<%= submit_tag 'Send' %>
<% end %>
The above code is working fine and the messages are getting sent, however, when I try to add the file field to it like so and try changing the controller code, the attachment is not getting uploaded :
def create_message
if params[:user].present? & params[:message].present? & params[:subject].present?
current_user.send_message(User.find(params[:user]), params[:message], params[:subject], true , params[:attachment])
redirect_to inbox_path
end
end
View :
<%= form_tag do %>
<%= select_tag 'user', options_from_collection_for_select(User.all, :id, :fullname) %><br/>
<%= text_field_tag 'subject' %><br/>
<%= text_area_tag 'message' %><br/>
<%= file_field_tag 'attachment' %>
<%= submit_tag 'Send' %>
<% end %>
I think this is a problem with the strong params. In Rails 3 I could have used attr_accessible. However how do I ensure that the attachment field is not being blocked and allowed?
P.S - I have the carrierwave gem installed and I have even restarted my server multiple times.
Thanks.
I am changing my previous answer, because in fact it wasn't correct.
Basically, if your problem is like mine, it could easily be solved by adding :multipart => true to your form. At least in my case, that's why carrierwave was not picking up the attachments.
I tried to solve the problem by extending the mailboxer Message class and setting up and mounting a completely new carrierwave object with a different attribute name. Basically, this allowed me to avoid working with the attachment attribute defined in mailboxer and to customize the attachments.
But this got very messy with the extension of the mailboxer message.rb Class. So I finally abandoned that course. Still, having your own uploader instead of relying on the mailboxer attachment is very convenient, especially if you want or need to upload your files to a different directory or to the cloud.
So finally, I have created a new model for my attachments and mounted a new carrierwave uploader on it. In that way, I can customize it as I want without having to tweak mailboxer, which has very little in terms of documentation or support.
Probably this is not useful to you anymore, but might help others!

Create an upload controller action for Rails app

I'm making a Rails app, and want to add an upload feature with allows users to upload multiple entries at once through an Excel spreadsheet as opposed to entering one entry at a time.
Ideally, I was hoping to add a separate Upload/Submit portion to the bottom of the new.html.erb file (the bold portion being the Upload HTML.erb):
...
<div class="actions">
<%= f.submit %>
</div>
<% end %>
**<div class="field">
Or Upload Multiple Entries <br />
<%= form_tag({:action => :upload}, :multipart => true) do %>
<%= file_field_tag 'multi_doc' %>
<% end %>
</div>**
Here is my routes.rb file:
Dataway::Application.routes.draw do
devise_for :users
resources :revenue_models do
get 'upload', :on => :collection
end
root :to => "home#index"
end
And my revenue_models_controller (haven't developed the action at all yet, now just a redirect):
...
def upload
redirect_to revenue_models_path
end
I have followed the rails guides for Uploading files as well as for Routing files and I keep getting an error when I attempt to open the /new view I have modified:
Routing Error
No route matches {:action=>"upload", :controller=>"revenue_models"}
Try running rake routes
When I run rake route, I get an entry for the upload action:
upload_revenue_models GET /revenue_models/upload(.:format) revenue_models#upload
In the end, what I would like to do is upload an excel file with multiple entries, parse it, and conditionally add each data row to my database, which I was under the impression I could specify in the upload action. Please help!
Please use form_for instead form_tag.
Second What is multi_doc is a field/attribute of revenue_model?. I guess is a field/attribute of revenue_model.
Third, Where is your instance variable revenue_model in the form?
Fourth, You have to create first a instance variable of your Model, on your action/controller where you are showing the form, for example #revenue_model = RevenueModel.new.
After try this code:
<%= form_for(#revenue_model, :method => :get, :html => {:multipart => true}, :url => { :controller => "revenue_models", :action => "upload"})) do |f| %>
<%= f.file_field :multi_doc %>
<%= f.submit :id => "any_id" %>
<% end %>
The question is very confusing, trying to clarify your question specifying the name of your actions and the names of the files in your views.
Regards!

paperclip - Invalid Parameter /Users PaperclipError: There was an error processing the thumbnail for stream

Trying to run paperclip on windows on a mongrel server. Images won't upload, generates console log of
Invalid Parameter - /Users
[paperclip] An error was received while processing: #<Paperclip::PaperclipError: There was an error processing the thumbnail for stream20110831-1316-1naludd>
The model code is
has_attached_file :image, :styles => { :large => "1280x800", :thumb => "128x80" }
Form code is
<%= simple_form_for #item, :html => { :multipart => true } do |f| %>
<%= f.error_messages %>
<%= f.input :name %>
<%= f.input :price %>
<%= f.input :description %>
<%= f.input :image %>
<%= f.association :section, :include_blank => false %>
<%= f.submit %>
<% end %>
Imagemagick is installed, path is placed in the development.rb file. Tried multiple image formats (.jpg, .png, .gif) from multiple locations. Migration has been done. Any ideas?
EDIT: SOLVED. Turns out I made a super stupid mistake and put forward slashes in the path to imageMagick, forgot for a second windows uses backslashes.
It looks like the ImageMagick convert utility can't process your uploaded image temp file.
Can you dump the environment for your mongrel? Especially wherever the Rails temp directory is.
I bet the fully qualified path to the 'tmp' directory in your Rails project isn't processable on windows when passed to ImageMagick, causing the thumbnail generation to fail.
Sadly, you may need to move your Rails project to a path that works.
Have the same problem, it aborts with the same error message when it tries to convert the image.
It's because convert is also a windows command (Better described here).
Changing paperclip's command_path in config/environments/development.rb directly to imagemagick solves the problem:
Paperclip.options[:command_path] = 'C:\Program Files\ImageMagick-6.9.0-Q16'

Resources