rails文件上传插件 acts_as_attachment 的实例
参考自:http://weblog.techno-weenie.net/articles/acts_as_attachment
重点词:acts_as_attachment、validates_as_attachment、uploaded_data
环境:InstantRails-2.0-win
1.创建rails工程及数据库railsacts_as_attachment_test-dsqlite3
cdacts_as_attachment_test
rakedb:create:all
2.安装插件acts_as_attachment
rubyscript\plugininstallhttp://svn.techno-weenie.net/projects/plugins/acts_as_attachment
3.生成迁移代码并且执行数据库迁移命令生成数据库
rubyscript/generateattachment_modelfile_list
rakedb: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
classFileList<ActiveRecord::Base
acts_as_attachment:storage=>:file_system,:file_system_path=>'public/files'
validates_as_attachment
end
5.创建控制器、方法及修改
rubyscript\generatecontrollerfileindexnewshowcreate
修改app\controllers\file_controller.rb文件如下
##app\controllers\file_controller.rb
classFileController<ApplicationController
defindex
@file=FileList.find(:all)
end
defnew
@file=FileList.new
end
defshow
@file=FileList.find(params[:id])
end
defcreate
@file=FileList.create(params[:file])
redirect_to:action=>'show',:id=>@file
rescueActiveRecord::RecordInvalid
render:action=>'new'
end
end
修改app\views\file\index.html.erb文件如下
<!--##app\views\file\index.html.erb-->
<h1>file</h1>
<ul>
<%@file.eachdo|f|-%>
<li><%=link_tof.filename,:action=>'show',:id=>f%></li>
<%end-%>
</ul>
<p><%=link_to'New',:action=>'new'%></p>
修改app\views\file\show.html.erb文件如下
<!--##app\views\file\show.html.erb-->
<p><%[email protected]%></p>
<%[email protected]_filename,:size=>@file.image_size%>
<p><%=link_to'Index',:action=>'index'%></p>
修改app\views\file\new.html.erb文件如下
<!--##app\views\file\new.html.erb-->
<h1>Newfile</h1>
<%form_for:file,:url=>{:action=>'create'},:html=>{:multipart=>true}do|f|-%>
<p><%=f.file_field:uploaded_data%></p>
<p><%=submit_tag'提交'%></p>
<%end-%>
6.启动服务,测试效果
startmongrel_railsstart-p3000
starthttp://127.0.0.1:3000/file