- rails new paperclip-sample-app
- cd paperclip-sample-app
- rails g scaffold user name:string email:string
- Before start using paperclip, we need to add it in our Gemfile.
gem ‘rails’, ‘3.2.13’
# Bundle edge Rails instead:
# gem ‘rails’, :git => ‘git://github.com/rails/rails.git’
gem ‘sqlite3’
gem “paperclip”, “~> 2.3”
- rails generate paperclip user avatar
- rake db:migrate
- open your model and check out the code below
class User < ActiveRecord::Base
attr_accessible :email, :name, :avatar
has_attached_file :avatar,
:styles => { :thumb => “75×75>”,
:small => “150×150>”
}
end
- then edit the new user form (app/views/users/_form.html.erb)
<%= form_for(@user, :html => { :multipart => true }) do |f| %>
<% if @user.errors.any? %>
<div id=”error_explanation”>
<h2><%= pluralize(@user.errors.count, “error”) %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :email %><br />
<%= f.text_field :email %>
</p>
<p>
<%= f.label :avatar %><br />
<%= f.file_field :avatar %>
</p>
<p>
<%= f.submit ‘Create’ %>
</p>
<% end %>
- then edit the new user form (app/views/users/index.html.erb)
<h1>Listing users</h1>
<table>
<tr>
<th>Photo</th>
<th>Name</th>
<th>Email</th>
</tr>
<% @users.each do |user| %>
<tr>
<td><%= image_tag user.avatar.url(:thumb) %></td>
<td><%= user.name %></td>
<td><%= user.email %></td>
<td><%= link_to ‘Show’, user %></td>
<td><%= link_to ‘Edit’, edit_user_path(user) %></td>
<td><%= link_to ‘Destroy’, user, method: :delete, data: { confirm: ‘Are you sure?’ } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to ‘New User’, new_user_path %>
Source:
- patshaughnessy.net
- codeabout.wordpress.com