Paperclip working on sign_out via devise - ruby-on-rails-3

I've recently added paperclip to add avatar to the users.
When a user sign out (using devise) I see this in the logs
Started DELETE "/signout" for 127.0.0.1 at 2012-11-04 17:23:15 +0200
Processing by Devise::SessionsController#destroy as HTML Parameters:
{"authenticity_token"=>"rHNBynyk546DcWTpGuARt2bdbSTtKPbw2ls+nDaihO8="}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" =
18 LIMIT 1 (0.0ms) BEGIN [paperclip] Saving attachments.
(0.0ms) COMMIT Redirected to http://localhost:3000/
my paperclip is really basic..
this in user.rb
has_attached_file :avatar,
:storage => :s3,
:bucket => ENV['BUCKET'],
:s3_credentials => {
:access_key_id => ENV['ACCESS_KEY'],
:secret_access_key => ENV['SECRET_KEY']
}
on user/_form.html.erb
<%= f.file_field :avatar %>
and on users/show.html.erb
<%= image_tag #user.avatar.url %>
what is paperclip doing there?
Is there a way to debug this?

See this answer: https://stackoverflow.com/a/4462445/432977
Basically paperclip will call the 'save' method on every attachment every time you update the model. But if no files are queued for delete or write, nothing will happen.

Related

rails-4 devise + user controller edit route redirecting to the wrong place

I am using devise gem in my app and a custom user controller. I have links to edit a user in both the show and index page. After signing in, if I click the edit link in users/index.html.erb or users/edit.html.erb, it redirects to user new form even though a GET request was sent.
In the route, I am skipping registrable because I am using the User controller to handle that and it works fine.
this is the route
devise_for :users, :path_prefix => 'd', skip: [:registrations], controllers: {sessons: "sessions"}
resources :users
rake routes | grep edit_user gives
edit_user_password GET /d/users/password/edit(.:format) devise/passwords#edit
edit_user GET /users/:id/edit(.:format) users#edit
users/show.html.erb
<div class="btn btn-primary"> <%= link_to "Edit", edit_user_path(#user) %></div>
This is the screenshot of the registration form that comes up when I click on the edit link in either the index or show page. It is making a get request but displaying the form for new instead of form for edit.
The is the log from clicking the edit link in the show page:
Started GET "/users/17/edit" for at 2013-08-19 08:40:49 +0000
Processing by UsersController#edit as HTML
Parameters: {"id"=>"17"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", "17"]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 17 ORDER BY "users"."id" ASC LIMIT 1
Rendered users/_form.html.erb (17.5ms)
Rendered users/edit.html.erb within layouts/application (26.8ms)
Completed 200 OK in 50ms (Views: 47.1ms | ActiveRecord: 0.5ms
The users_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, except: [:new, :create]
respond_to :html, :json
def show
end
def edit
end
private
def set_user
#user = User.find(params[:id])
end
end
users/_edit.html.erb I even specified url path in the form and it still renders new form
form_for(#user, :url => edit_user_path(#user))
users/edit.html.erb
<%= render "edit" %>
users/index.html.erb
<% #users.each do |user| %>
<div class="btn btn-primary"><%= link_to "Edit", edit_user_path(user) %> </div>
<div class="btn btn-danger"><%= link_to 'Remove', user, method: :delete, data: {confirmation: 'Are you sure'} %></div>
<% end %>
You are making a POST request to the edit user path whereas this path is registered with the GET method. That's why you get this error.
Personally, instead of skipping the registration, I would have overwritten the registrations controller as described in the Devise wiki.

Issue updating file attachment(image) using Attachment_fu

I am able to upload image files as attachments using Attachment_fu but when I try to edit/ modify images which were already uploaded, it does not work.
In my Controller I have this:
def update
#sponsor_account = SponsorAccount.find( params[:id] )
if params[:showcase_category_image_file] &&
!params[:showcase_category_image_file].blank?
#sponsor_account.showcase_category_image =
ShowcaseCategoryImage.new(:uploaded_data =>
params[:showcase_category_image_file])
***This logs - Now the file name is: ***
Rails.logger.info("Now the file name is: #
{#sponsor_account.showcase_category_image.filename}")
end
#sponsor_account.update_attributes( params[:sponsor_account] )
if #sponsor_account.save
flash[:notice] = "Showcase category #{#sponsor_account.name} was updated!"
else
flash[:errors] = #sponsor_account.errors
end
redirect_to sponsor_accounts_path
end
ShowcaseCategoryImage is defined as follows:
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 5.megabytes,
:thumbnails => { :large => [350, 100], :medium => [200, 90], :thumb =>
[35,35], :preview => [60,60] }
validates_as_attachment
The view has a file_field_tag as follows:
<%= file_field_tag :showcase_category_image_file%>
and my SponsorAccount model says:
has_one :showcase_category_image, :as => :owner, :dependent => :destroy
validates_presence_of :showcase_category_image, :on => :create
Almost similar code works perfectly ok in 'create' but here in 'update' action where there is already a value, this code is not working.
I am getting the below error msgs:
Completed 500 Internal Server Error in 1089ms
ActionView::Template::Error (undefined method `public_filename' for nil:NilClass):
Obviously this error is in the index action where it tries to list all records and their attachments. Since this attachment is empty after the update, this error is thrown in the redirect_to part.
I am using REE1.8.7 and rails 3.2.9
Please help!
This issue was solved when I added :multipart => true in the 'View'. I am using rails 3.2.9 and the rails api has this to say about the 'file_field_tag':
file_field_tag(name, options = {}) Link
Creates a file upload field. If you are using file uploads then you will also need to set the multipart option for the form tag:

storing complex records in rails database with form_tag

I'm trying to save records in a database. Many of the column values will be taken from a http request to an api.
I have a text field and some check boxes along with the session_id in the form which will be persisted. this is posted from another controller (form_tag('results#store'))to an action called store in the results controller.
Store action:
def store
query = query_preprocesser(params[:query]) # this is in a helper
## example of resArray ##
#resArray = [[{:engine => "bing, :results => [{:Description => "abc", :Title => "def"}, {:Description => "ghi", :Title => "jkl"}]}, {etc},{etc} ],[{:eng...}]]
resArray = getResults(query) # Also a helper method returning an array of up to 3 arrays
resArray.each do |engine|
db_name = engine[:engine]
engine[:results].each do |set|
res = Result.new(
:session_id => params[:session_id],
:db_name => db_name,
:query => query,
:rank => set[:Rank],
:description => set[:Description],
:title => set[:Title],
:url => set[:Url] )
res.save!
end
end
res.each do |res|
res.save
end
#Result.new(:session_id => params[:session_id], :db_name => "Bing", :query => "Whats the story", :query_rank => 1, :title => "The Title", :description => "descript", :url => "www.google.ie",:query_number => 1)
respond_to do |format|
format.html { redirect_to pages_path }
format.json { head :no_content }
end
end
My routes are resources :results
Server logs:
[2012-07-10 23:30:48] INFO WEBrick 1.3.1
[2012-07-10 23:30:48] INFO ruby 1.9.3 (2012-04-20) [x86_64-linux]
[2012-07-10 23:30:48] INFO WEBrick::HTTPServer#start: pid=15584 port=3000
Started POST "/results" for 127.0.0.1 at 2012-07-10 23:31:36 +0100
Connecting to database specified by database.yml
Processing by ResultsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"/nTJOF5Ab+XnL+jxRBHnTJz45YRVmgbf55bmn5/iz8E=", "query"=>"search term", "button"=>"", "searchType"=>"Seperate", "bing"=>"1", "session_id"=>"e08c13a99f21a91520fcc393e0860c94"}
(0.2ms) begin transaction
(0.2ms) rollback transaction
Rendered results/_form.html.erb (13.9ms)
Rendered results/new.html.erb within layouts/application (23.6ms)
Completed 200 OK in 213ms (Views: 78.4ms | ActiveRecord: 2.9ms)
Form:
<%= form_tag('results#store') do %>
Rake routes:
store POST /pages(.:format) results#store
results GET /results(.:format) results#index
POST /results(.:format) results#create
new_result GET /results/new(.:format) results#new
edit_result GET /results/:id/edit(.:format) results#edit
result GET /results/:id(.:format) results#show
PUT /results/:id(.:format) results#update
DELETE /results/:id(.:format) results#destroy
store POST /pages(.:format) results#store
pages GET /pages(.:format) pages#index
I keep getting redirected to the new action in Results controller. The helper methods aren't even being executed. I'm a past master at over complicating things, can anyone help unravel this for me?
Do you have a route set up for the store action? If you do then you should use the url helper for it in your form tag:
form_tag( results_store_url )

update action not saving data

I am having trouble getting a form text area to update a field in a rails 3.0.8 app. I keep stripping out as much as i can to narrow down where the error lies. Here's what is left.
My form:
<%= form_for #fb_comments, :remote => true, :html => { :'data-type' => 'html', :id => 'comment' } do |form| %>
<%= form.text_area :comment %>
<%= form.submit "Update Comments" %>
<% end %>
The dummy data that i put into the comment column via mysql for this record shows up so the current data is making it to the form.
controller:
def update
fbc = FbComments.find(params[:id])
fbc.update_attributes(params[:comment])
...
end
console message:
Started POST "/fb_comments/1" for 127.0.0.1 at 2011-06-13 17:31:43 -0400
Processing by FbCommentsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gLA2A11uVRl/WtIR1p90aSkLoU6b8twotK+B1YNefRk=", "fb_comments"=>{"comment"=>"test test"}, "commit"=>"Update Comments", "id"=>"1"}
FbComments Load (0.1ms) SELECT `fb_comments`.* FROM `fb_comments` WHERE `fb_comments`.`id` = 1 LIMIT 1
SQL (0.1ms) BEGIN
SQL (0.1ms) COMMIT
Rendered text template (0.0ms)
Completed 200 OK in 15ms (Views: 0.6ms | ActiveRecord: 0.3ms)
Thanks.
Your controller is recieving fb_comments not comment:
fbc.update_attributes(params[:fb_comments])
Hoe this helps.

Paperclip not called when uploading attachment, so attachment is not saved. Rails3 + uploadify

I have two different apps using paperclip. On the app that does not save attachment or call paperclip, i get this log when i upload an app
started POST "/users/1/uploads" for 127.0.0.1 at 2011-04-23 13:38:11 +0100
Processing by UploadsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"t2dRIH4FgOPnLRhpDK0x7iIfjB9Xj5rqkJRPCWZvJ14=", "upload"=> {"document"=>#<ActionDispatch::Http::UploadedFile:0x2beeb08 #original_filename="Essay questions have various requirements.doc", #content_type="application/msword", #headers="Content-Disposition: form-data; name=\"upload[document]\"; filename=\"Essay questions have various requirements.doc\"\r\nContent-Type: application/msword\r\n", #tempfile=#<File:C:/DOCUME~1/Ed/LOCALS~1/Temp/RackMultipart20110423-3980-ycq74p>>}, "commit"=>"Upload", "user_id"=>"1"}
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
[1m[36mUpload Load (0.0ms)[0m [1mSELECT "uploads".* FROM "uploads" WHERE ("uploads".uploadable_id = 1 AND "uploads".uploadable_type = 'User')[0m
Rendered uploads/_uploadify.html.erb (15.6ms)
Rendered uploads/_form.html.erb (31.2ms)
Rendered uploads/new.html.erb within layouts/application (46.9ms)
Completed 200 OK in 500ms (Views: 234.4ms | ActiveRecord: 0.0ms)
On the app where paperclip works fine, i get this log:
Started POST "/uploads" for 127.0.0.1 at Mon Apr 25 11:35:50 +0100 2011
Processing by UploadsController#create as JSON
Parameters: {"_http_accept"=>"application/javascript", "Filename"=>"angels.txt", "folder"=>"/users/", "authenticity_token"=>"NVJj3ODIGuoc97wGvjWkez1YoN+SUDVtNJ+k80XdYXM=", "Upload"=>"Submit Query", "user_id"=>"1", "_uploadify_session"=>"BAh7ByIQX2NzcmZfdG9rZW4iMU5WSmozT0RJR3VvYzk3d0d2aldrZXoxWW9OK1NVRFZ0TkorazgwWGRZWE09Ig9zZXNzaW9uX2lkIiU0ZDEyNzZkNzczNzk1MDdiMmQ4NWZmYTY5MDY4YTU0MQ==--7eb8c0ca249e2566998a0e68322a89d731fdb4ad", "Filedata"=>#<ActionDispatch::Http::UploadedFile:0x4958490 #content_type="application/octet-stream", #original_filename="angels.txt", #tempfile=#<File:C:/DOCUME~1/Ed/LOCALS~1/Temp/RackMultipart20110425-4884-vyvdo8-0>, #headers="Content-Disposition: form-data; name=\"Filedata\"; filename=\"angels.txt\"\r\nContent-Type: application/octet-stream\r\n">}
[paperclip] identify -format %wx%h "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110425-4884-15he32x-0.txt[0]" 2>NUL
[paperclip] convert "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-0.txt[0]" -resize "300x300>" "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-020110425-4884-r65fe6-0" 2>NUL
[paperclip] identify -format %wx%h "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-0.txt[0]" 2>NUL
[paperclip] convert "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-0.txt[0]" -resize "100x100>" "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-020110425-4884-1ttxfol-0" 2>NUL
[1m[36mAREL (15.6ms)[0m [1mINSERT INTO "uploads" ("user_id", "created_at", "photo_file_size", "photo_updated_at", "photo_content_type", "photo_file_name", "updated_at") VALUES (1, '2011-04-25 10:36:10.312500', 867, '2011-04-25 10:35:52.109375', 'text/plain', 'angels.txt', '2011-04-25 10:36:10.312500')[0m
[paperclip] Saving attachments.
[paperclip] saving C:/rails_project1/Uploadify-2/public/system/photos/2/medium/angels.txt
[paperclip] saving C:/rails_project1/Uploadify-2/public/system/photos/2/thumb/angels.txt
[paperclip] saving C:/rails_project1/Uploadify-2/public/system/photos/2/original/angels.txt
Completed 200 OK in 19422ms (Views: 62.5ms | ActiveRecord: 15.6ms)
The only difference between the two is that the one not working is polymorphic model and the controller for the polymorphic model is below:
class UploadsController < ApplicationController
before_filter :find_parent
before_filter :prepare_input_params
#respond_to :html, :json, :js
def index
#uploads = Upload.all
##uploads = #parent.try(:uploads).try(:all)
#upload = Upload.new
#respond_with([#parent, #uploads])
end
def new
#upload = #parent.uploads.new
end
def create
#upload = #parent.uploads.build(params[:upload])
if #upload.save
flash[:notice] = "sucessfully saved upload"
respond_to do |format|
format.html {redirect_to [#parent, :uploads]}
format.json {render :json => { :result => 'success', :upload => polymorphic_url([#parent,:uploads]) } }
end
else
render :action => 'new'
end
end
def edit
#upload = Upload.find(params[:id])
end
def show
"puts #upload.inspect"
#upload = #parent.uploads.find(params[:id])
#total_uploads = #parent.uploads.find(:all, :conditions => { :user_id => #upload.user.id})
end
def update
#upload = Upload.find(params[:id])
if #upload.update_attributes(params[:upload])
flash[:notice] = "Successfully updated document"
redirect_to #upload
else
render :action => 'edit'
end
end
def destroy
#upload = Upload.find(params[:id])
#upload.destroy
redirect_to([#parent, :upload])
end
private
def prepare_input_params
params[:upload][:document] = params[:Filedata] if params[:Filedata]
end
end
Here is the gist file with the form partial and uploadify bit: https://gist.github.com/940960. The form has :html => { :multipart => true }.
Thanks for the help.
EDIT:
It seems the problem is from the model, uploads.rb. When i comment out the section below: everything works, but i need to be able to use validations and specify path as i want to use S3. Anyhelp on how i can uncomment the code without the initial error of paperclip not saving happening again.
class Upload < ActiveRecord::Base
attr_accessible :document
belongs_to :uploadable, :polymorphic => true
has_attached_file :document, :styles => { :small => "150x150>",:thumb => "100x100>" }
=begin
:url => "/uploads/:id/:style/:basename.:extension",
:path => ":rails.root/public/:uploads/:id/:style/:basement.:extension"
validates_attachment_presence :document
validates_attachment_size :document, :less_than => 5.megabytes
validates_attachment_content_type :document, :content_type => ['application/octet-stream','image/jpeg','image/gif', 'image/png', 'image/pdf', 'image/doc',
'video/x-m4v', 'video/quicktime','application/x-shockwave-flash', 'audio/mpeg', 'video/mpeg', 'application/pdf','application/msword']
=end
end
Update:
I think the main problem seem to be that why attaching a new file, paperclip, somehow starts calling SELECT "uploads".*'from "uploads" instead of calling INSERT INTO 'uploads', that is controller#create action shown higher up seems to be calling SELECT, whenever ever i provide :url and :path options to paperclip has_attached_file method. See the log below:
Processing by UploadsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Azxzi09R7NU7+jxj+lxHFGfs+qw7D6b7yRKegRjRQMc=", "upload"=> {"document"=>#<ActionDispatch::Http::UploadedFile:0x2994ff0 #original_filename="al night verses.txt", #content_type="text/plain", #headers="Content-Disposition: form-data; name=\"upload[document]\"; filename=\"al night verses.txt\"\r\nContent-Type: text/plain\r\n", #tempfile=#<File:C:/DOCUME~1/Ed/LOCALS~1 /Temp/RackMultipart20110505-3444-1rlpnr>>}, "commit"=>"Upload", "user_id"=>"1"}
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
[paperclip] C:\ImageMagick-6.6.3-Q16/identify -format %wx%h "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf87.txt[0]"
[paperclip] C:\ImageMagick-6.6.3-Q16/convert "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf87.txt[0]" -resize "150x150>" "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf8720110505-3444-1vnp5jx"
[paperclip] C:\ImageMagick-6.6.3-Q16/identify -format %wx%h "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf87.txt[0]"
[paperclip] C:\ImageMagick-6.6.3-Q16/convert "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf87.txt[0]" -resize "100x100>" "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf8720110505-3444-1vyk9i"
[1m[36mUpload Load (0.0ms)[0m [1mSELECT "uploads".* FROM "uploads" WHERE ("uploads".uploadable_id = 1 AND "uploads".uploadable_type = 'User')[0m
Rendered uploads/_uploadify.html.erb (15.6ms)
Rendered uploads/_form.html.erb (31.2ms)
Rendered uploads/new.html.erb within layouts/application (62.5ms)
Based on #CharlieMezak's request, here is the views/uploads/_form.html.erb:
<%= debug #parent %>
<%= render :partial => "uploads/uploadify" %>
</br>
<%= form_for [parent, upload], :html => { :multipart => true } do |f| %>
<div class="field">
<%= f.label :document %><br />
<%= f.file_field :document %>
</div>
<div class="actions">
<%= f.submit "Upload"%>
</div>
views/uploads/new.html.erb:
<%= render 'form', :parent => #parent, :upload => #upload %>
views/users/index.html.erb:
<%= render "uploads/form", :parent => user, :upload => user.uploads.new %>
More Update :
Like i mentioned, when i comment out the :styles, : :url and :path options from paperclips's **'has_many_attachment :document', the INSERT statement is called and though it saves the file, instead of displaying the attached file, it ends up displaying several parameters like authenticity tokens etc on the website as shown below:
attributes:
id: 1
email: xyz#yahoo.com
encrypted_password: $2a$10$HiksbkRXDtcXiJyUIRj
password_salt: $2a$10$HiksbkRXD
reset_password_token: !!null
remember_token: !!null
remember_created_at: !!null
sign_in_count: 3
current_sign_in_at: '2011-04-25 18:57:27.078125'
last_sign_in_at: '2011-04-25 09:25:31.406250'
current_sign_in_ip: 127.0.0.1
last_sign_in_ip: 127.0.0.1
created_at: '2011-04-09 17:46:15.546875'
updated_at: '2011-04-25 18:57:27.078125'
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false
Did you remember to add :multipart => true to the form tag in your view?
Try adding :document_file_name to the attr_accessible call.
One thing I noticed is there is a typo on line 17 of uploadify in your gist. You have dat.upload, probably should be data.upload?
Also, have you tried uncommenting the validations one at a time? Let me know what happens. I've had my fair share of battles versus Paperclip.
I'm doing exactly the same kind of thing as you are, but using the aws-s3 gem to help me upload to S3 via paperclip. This is what's in my model:
has_attached_file :image,
:storage => :s3,
:s3_credentials => "#{Rails.root.to_s}/config/s3.yml",
:bucket => "your_s3_bucket_name",
:path => ":attachment/:id/:style/:filename"
And I have this in my gemfile:
gem "paperclip", "~> 2.3"
gem "aws-s3"
And in my groups table:
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"