Tuesday, July 13, 2010

Attach file in rails

  • First you will need to install " paperclip " gem for ruby.
  • in your terminal write " sudo gem install paperclip -v=2.3.3 "
    • this will install the gem but won't activate it for your application.
    • To activate it you have to go to you environment.rb  file and write the following line:
      • " config.gem "paperclip", :version => '2.3.3' "
    • now your application will load the gem when he start.
Let's take an example as you want to make an avatar to your users. In this case you will need to upload image for each user when he signup or edit his/her profile.

Lets code:

  • In user model:
  • class User < ActiveRecord::Base
        has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
      end
  • Create migration to edit your user table:

ruby script/generate migration add_avatar_columns_to_user
  • Now the migration file:  




  • Update your DB:
rake db:migrate 
  • In your edit and new view:

  • In your show view:

No comments:

Post a Comment