Wednesday, 29 August 2012

Mongoid::Paperclip


Mongoid::Paperclip - Making Paperclip play nice with Mongoid 

1st Install Image Magick using

$ sudo apt-get install imagemagick

As the title suggests: Mongoid::Paperclip makes it easy to hook up Paperclip with Mongoid.
This is actually easier and faster to set up than when using Paperclip and the ActiveRecord ORM. This example assumes you are using Ruby on Rails 3 and Bundler. However it doesn't require either.

Setting it up

Simply define the mongoid-paperclip gem inside your Gemfile. Additionally, you can define the aws-s3 gem if you want to upload your files to Amazon S3. You do not need to explicitly define the paperclip gem itself, since this is handled bymongoid-paperclip.
Rails.root/Gemfile - Just define the following:
gem "mongoid-paperclip", :require => "mongoid_paperclip"
gem "aws-s3",            :require => "aws/s3"
Next let's assume we have a User model and we want to allow our users to upload an avatar.
Rails.root/app/models/user.rb - include the Mongoid::Paperclip module and invoke the provided class method
class User
  include Mongoid::Document
  include Mongoid::Paperclip

  has_mongoid_attached_file :avatar
end

That's it

That's all you have to do. Users can now upload avatars. Unlike ActiveRecord, Mongoid doesn't use migrations, so we don't need to define the Paperclip columns in a separate file. Invoking the has_mongoid_attached_file method will automatically define the necessary :avatar fields for you in the background.

include  :html => { :multipart => true } for form.

No comments:

Post a Comment