首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

rails文件下传插件 acts_as_attachment 的实例

2012-11-22 
rails文件上传插件 acts_as_attachment 的实例参考自:http://weblog.techno-weenie.net/articles/acts_as_

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工程及数据库


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文件如下


<!--##app\views\file\index.html.erb-->
<h1>file</h1>
<ul>
<% @file.each do |f| -%>
??<li><%= link_to f.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><%= @file.filename %></p>
<%= image_tag @file.public_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>New file</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.启动服务,测试效果


start mongrel_rails start -p 3000
start http://127.0.0.1:3000/file

?

热点排行