Mongoid::Paperclip
The ‘mongoid-paperclip’ gem is specially used in rails application with mongodb database where as the ‘paperclip’ gem is use in rails application with other than mongodb database like mysql, postgreSQL etc.Before start this tutorial make sure that the ‘mongoid’ gem is already installed in your application. Lets follow following steps:
1. Include the gem in your Gemfile
gem "mongoid-paperclip", :require => "mongoid_paperclip"
2. Install gem (run on command prompt):
bundle install
3. Create controller (say Image ):
rails g controller Images index new show
4. Create model (say Image):
rails g model Image
5. Add following code in app/models/image.rb
class Image
include Mongoid::Document
include Mongoid::Paperclip
has_mongoid_attached_file :image
validates_attachment_content_type :banner_image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
6. Add following code in images controller.
def new
@images=Image.new
end
6. Use following code to create form (in views/Images/new.html.erb)
<%= form_for(@images, :url => {:action => 'create'}, :html => {:multipart => true}) do |f| %>
<%= f.file_field :image %>
<%= f.submit "Upload" %>
<% end %>
7. Use following code to Upload image (in ‘create’ action of controllers/image_controller.rb)
def create
@image = Image.new(images_params)
if @image.save
redirect_to :action => :show, :id => @image.id
end
end
8. Use following code to view uploaded image (in ‘show’ action of controllers/image_controller.rb)
@id = params[:id]
@image = Image.find(@id)
9. and add in (views/image/show.html.erb)
<%= image_tag @image.image.url %>
10. Start server and run on browser:
localhost:3000/images/new
11. your images will saved in /public/system/images/image..
If you want see path of image..
in your terminal..
rails c
Image.last.image.url(:default)
12. if you want to add styles to your image..like specific width...use below code in your model
has_mongoid_attached_file :banner_image, :styles => { :default => "598x246>"}
13.Help Ful links:
https://github.com/thoughtbot/paperclip/wiki/Thumbnail-Generation
U are using same image with different sizes in same project u can define three styles as follows:
has_mongoid_attached_file :image, :styles => { :small=> '124x89',:medium=> '247x173',:large=> '598x299'}
Then u can access image as following way:
<%= image_tag @image.image.url(:large) %> #for large image
<%= image_tag @image.image.url(:small) %> #for small image
<%= image_tag @image.image.url(:medium) %> #for medium image
If u make any changes..need to apply total images in ur table just simpl run below command:
rake paperclip:refresh CLASS=Events::Photo Happy Learning.......
is it write very clearly but it is not working and some changes is there and you write first basic step start very clearly
ReplyDeleteHi naresh,
DeleteDid you managed to find a working one. Im struck with same problem. not working.?
Let me know at mohanbabu.bb@gmail.com
Thanks,
MB