ruby -- 进阶学习(二)paperclip上传图片

时间:2023-03-10 06:38:02
ruby -- 进阶学习(二)paperclip上传图片

Need to add image attachments to a model? See how with paperclip in this episode.

在命令行输入:

rails g paperclip product photo
rake db:migrate

注:product是你要添加属性的models中的.rb文件名,photo是要插入的图片在数据表中的属性名

配置models/product.rb

has_attached_file :photo, :styles => { :small => "150x150>" },
:url => "/assets/products/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/products/:id/:style/:basename.:extension" validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 5.megabytes
validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png']

配置products/_form.html.erb

<%= image_tag @product.photo.url(:small) %>

配置products/show.html.erb

<% form_for @product, :html => { :multipart => true } do |f| %>
...
<%= f.file_field :photo %>
...
<% end %>

原文链接:http://railscasts.com/episodes/134-paperclip