---
title: "快闪行动-->为你的项目添加标签模块"
author: "fireflyman"
date: "2011-04-23T16:44:53Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-05-01T13:13:46Z"
id: 1013620
url: "https://fireflyman.iteye.com/blog/1013620"
---

在开始之前,还是要不厌其烦的说说,那些不必要写的你自己搞把,反正大把人玩过...
1.安装插件-->

```Ruby
ruby script/plugin install git://github.com/jviney/acts_as_taggable_on_steroids.git
```



```Ruby
ruby script/generate acts_as_taggable_migration
```



```Ruby
rake db:migrate
```


-->这时你会有两个表:tags+taggings

2.针对我的TODO现况,接下去如下:
**Model**

```Ruby

class Photo < ActiveRecord::Base
   acts_as_taggable
end
```

**Controller**

```Ruby

class PhotosController < ApplicationController


def index
    @photos = Photo.paginate(:page =>params[:page]||1,
                             :per_page =>10,
                             :order=>"updated_at DESC")
   tag_cloud
      
    respond_to do |format|
      format.html # index.html.erb
      format.xml { render :xml => @photos }
    end
end

#tag method
   def tag_cloud
      @tags = Photo.tag_counts
   end

   def tag
       @photos= Photo.find_tagged_with(params[:id])
   end

```

**Helper**

```Ruby

module ApplicationHelper
  include TagsHelper
end
```


**View**
1). 添加标签:在new.html.erb中,

```Ruby
<p>
    <%= f.label :tags,'标签' %><br />
    <%= f.text_field :tag_list,:size=>'60' %>*多个标签以","隔开
</p>
*注意: tag_list字段并不在 Item表中有,多个标签以","隔开

```

2). 显示标签,在index.html.erb中,

```Ruby
<div style="padding:20px">
tags: <% tag_cloud @tags, %w(css1 css2 css3 css4) do |tag, css_class| %>
    <%= link_to tag.name, {:action => :tag, :id => tag.name }, :class => css_class %>
     <% end %>
</div>
```

3). 显示标签详细:新建一个文件: photos/tag.erb

```Ruby
<% @photos.each do |photo| %>
<tr>
    <td><%=h photo.title %></td>
</tr>
<% end %>
```

只作参考,请勿评论~