paperclip是rails的一个上传文件的包,简单学习了一下。
https://github.com/thoughtbot/paperclip,官方教程。
ImageMagick,教程中指出必须安装,我用的是Ubuntu 12.04LTS,提示已经安装好了。
使用方法:
在相应model中添加:
class User < ActiveRecord::Base attr_accessible :avatar has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png" end
在相应migration中添加:
class AddAvatarColumnsToUsers < ActiveRecord::Migration def self.up add_attachment :users, :avatar end def self.down remove_attachment :users, :avatar end end
Or you can use migration generator: rails generate paperclip user avatar.
在view中添加编辑框:
<%= form_for @user, :url => users_path, :html => { :multipart => true } do |form| %> <%= form.file_field :avatar %> <% end %>
最后在显示view中:
<%= image_tag @user.avatar.url %>
取消关联:
@user.avatar = nil @user.save
编辑存放路径:
has_attached_file :photo, :url => "/assets/users/:attachment/:id/:style/:basename.:extension", :path => ":rails_root/public/assets/users/:attachment/:id/:style/:basename.:extension"