---
title: "rails文件上传插件 acts_as_attachment 的实例 "
author: "xinlanzero"
date: "2011-08-09T14:30:38Z"
tags: []
categories: ["Web前端"]
slug: "rails-acts-as-attachment"
draft: false
lastmod: "2011-08-09T14:30:58Z"
id: 1143467
url: "https://xinlanzero.iteye.com/blog/1143467"
---

参考自：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 &lt; ActiveRecord::Base  
  acts\_as\_attachment :storage =&gt; :file\_system ,:file\_system\_path =&gt; '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 &lt; 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 =&gt; 'show' ,:id =&gt; @file  
    rescue ActiveRecord::RecordInvalid  
    render :action =&gt; 'new'  
  end

end

修改app\\views\\file\\index.html.erb文件如下

&lt;!--##app\\views\\file\\index.html.erb--&gt;  
&lt;h1&gt;file&lt;/h1&gt;  
&lt;ul&gt;  
&lt;% @file.each do |f| -%&gt;  
  &lt;li&gt;&lt;%= link\_to f.filename, :action =&gt; 'show', :id =&gt; f %&gt;&lt;/li&gt;  
&lt;% end -%&gt;  
&lt;/ul&gt;  
&lt;p&gt;&lt;%= link\_to 'New', :action =&gt; 'new' %&gt;&lt;/p&gt;

修改app\\views\\file\\show.html.erb文件如下

&lt;!--##app\\views\\file\\show.html.erb--&gt;  
&lt;p&gt;&lt;%= @file.filename %&gt;&lt;/p&gt;  
&lt;%= image\_tag @file.public\_filename, :size =&gt; @file.image\_size %&gt;  
&lt;p&gt;&lt;%= link\_to 'Index', :action =&gt; 'index' %&gt;&lt;/p&gt;

修改app\\views\\file\\new.html.erb文件如下

&lt;!--##app\\views\\file\\new.html.erb--&gt;  
&lt;h1&gt;New file&lt;/h1&gt;  
&lt;% form\_for :file, :url =&gt; { :action =&gt; 'create' }, :html =&gt; { :multipart =&gt; true } do |f| -%&gt;  
  &lt;p&gt;&lt;%= f.file\_field :uploaded\_data %&gt;&lt;/p&gt;  
  &lt;p&gt;&lt;%= submit\_tag '提交' %&gt;&lt;/p&gt;  
&lt;% end -%&gt;

6.启动服务，测试效果

start mongrel\_rails start -p 3000  
start http://127.0.0.1:3000/file