Saturday, 22 September 2012

Update image using paperclip: Rails way

Paperclip is a nice and widely preferred way of uploading datasets into your rails application.

Installation of paperclip:

Add "gem "paperclip"  in your gem file
run 'bundle install'
Restart the server
----------

Once installed you're now ready to use it.

1) In your model you don't need to create any new attributes by yourself .
If you have already added any dataset upload attribute then remove it
2) run rails script to add attributes to your model

rails g paperclip model_name  attribute_name
eg.
  rails g paperclip user avatar

output:  Migration file inside db/migrate/20120922114200_add_attachment_avatar_to_users.rb

Run the migration:
  rake db:migrate VERSION=20120922114200
=> It'll run all the migration till this latest timestamp.

To run only this migration in case of you messed up with your old migrations
rails console
require "db/migrate/20120922114200_add_attachment_avatar_to_users.rb"
true
AddAttachmentAvatarsToUsers.up

Once done, you now need to define association in your model. i.e user.rb
  

  attr_accessible :name, :description, :avatar
  has_attached_file :photo, :styles=> { :medium=>"300x300", :thumb=>"100x100" },
:url =>"/assets/menus/:id/:style/:basename.:extension",
:path=>":rails_root/public/assets/menus/:id/:style/:basename.:extension"
...
  validates_attachment :photo, :content_type => {:content_type=> ["image/jpg", "image/png"] }, :size=> {:in =>  5..500.kilobytes}



Validations available:                                         

  • AttachmentContentTypeValidator
  • AttachmentPresenceValidator
  • AttachmentSizeValidator


validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 5.megabytes
validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png']


Or you can write in single line as :

  validates_attachment :photo, :content_type => {:content_type=> ['image/jpeg', 'image/gif', 'image/png', 'image/pjpeg', 'image/x-png' ] }, :size=> {:in =>  5..500.kilobytes}

File saving path                                                 


has_attached_file :photo, :styles=> { :medium=>"300x300", :thumb=>"100x100" },
:url =>"/assets/menus/:id/:style/:basename.:extension",
:path=>":rails_root/public/assets/menus/:id/:style/:basename.:extension"



In the form do this:                                           
1) Set multipart to true
2) add file_field

eg.

<% form_for @user, :html => { :multipart => true } do |f| %>
  ...
  <%= f.file_field :avatar%>
  ...
<% end %>


Paperclip Update , Create and Delete cases                        

class UploadsController < ApplicationController def index @uploads = Upload.scoped end def new @upload = Upload.new end def edit @upload = Upload.find(params[:id]) end def create @upload = Upload.new(params[:upload]) if @upload.save flash[:notice] = 'Upload was successfully created' redirect_to uploads_url else render 'new' end end def update @upload = Upload.find(params[:id]) if @upload.editable? && @upload.update_attributes(params[:upload]) flash[:notice] = 'Upload was successfully updated' redirect_to uploads_url else render 'edit' end end def destroy @upload = Upload.find(params[:id]) if @upload.destroy flash[:notice] = 'Upload was successfully deleted' end redirect_to uploads_url end end

Errors:

1) Error : Can't dump file
Solution:   Destroy image object in case of error.
                How to destroy image object?
              Ans: simply assign it to 'nil'  eg. @menu.photo = nil


if @menu.save
flash[:success] ="New menu created successfully."
redirect_to :action=>"index"
else
flash[:error]= @menu.errors
@menu.photo = nil
redirect_to :action=>"new"
end

1) Error : ...not recognized by the 'identify' command.

photo C:/Users/naresh/AppData/Local/Temp/197739_10150928236101192_1275359865_n20120922-20928-l1wbbv.jpg is not recognized by the 'identify' command.
photo C:/Users/naresh/AppData/Local/Temp/197739_10150928236101192_1275359865_n20120922-20928-l1wbbv.jpg is not recognized by the 'identify' command.
photo_file_size must be in between 5 Bytes and 512000 Bytes
Solution:
Install imagemagick and rmagick gem
Tutorial is given here in my previous post. Installing Rmagick 

No comments:

Post a Comment