参考自:http://weblog.techno-weenie.net/articles/acts_as_attachment
重点词:acts_as_attachment 、validates_as_attachment、uploaded_data
环境:InstantRails-2.0-win
1.创建rails工程及数据库
rails acts_as_attachment_test -d sqlite3
cd acts_as_attachment_test
rake db:create:all
2.安装插件acts_as_attachment
ruby script\plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_attachment
3.生成迁移代码并且执行数据库迁移命令生成数据库
ruby script/generate attachment_model file_list
rake db:migrate
4.修改app\models\file_list.rb文件如下,更详细的限制文件大小、类型==参考vendor\plugins\acts_as_attachment\lib\technoweenie\acts_as_attachment.rb文件27-38行
##app\models\file_list.rb
class FileList < ActiveRecord::Base
acts_as_attachment :storage => :file_system ,:file_system_path => 'public/files'
validates_as_attachment
end
5.创建控制器、方法及修改
ruby script\generate controller file index new show create
修改app\controllers\file_controller.rb文件如下
##app\controllers\file_controller.rb
class FileController < ApplicationController
def index
@file = FileList.find(:all)
end
def new
@file = FileList.new
end
def show
@file = FileList.find(params[:id])
end
def create
@file = FileList.create (params[:file])
redirect_to :action => 'show' ,:id => @file
rescue ActiveRecord::RecordInvalid
render :action => 'new'
end
end
修改app\views\file\index.html.erb文件如下
file
- <%= link_to f.filename, :action => 'show', :id => f %>
<% @file.each do |f| -%>
<% end -%>
<%= link_to 'New', :action => 'new' %>
修改app\views\file\show.html.erb文件如下
<%= @file.filename %>
<%= image_tag @file.public_filename, :size => @file.image_size %>
<%= link_to 'Index', :action => 'index' %>
修改app\views\file\new.html.erb文件如下
New file
<% form_for :file, :url => { :action => 'create' }, :html => { :multipart => true } do |f| -%>
<%= f.file_field :uploaded_data %>
<%= submit_tag '提交' %>
<% end -%>
6.启动服务,测试效果
start mongrel_rails start -p 3000
start http://127.0.0.1:3000/file