用Rails 2.3打造简单记账软件(12)

January 5th, 2010 (579 views)

在这以前我们把tags作为Entry的一个字段来实现,这样做有很大的局限性,而且还有好多插件可以实现这个功能,现在我们就来把它替换用插件acts_as_taggable_on_steroids实现。

安装插件

script/plugin install git://github.com/jviney/acts_as_taggable_on_steroids.git
script/generate acts_as_taggable_migration
rake db:migrate

在Entry中添加一句代码

class Entry < ActiveRecord::Base
  acts_as_taggable

  belongs_to :user
end

还要将所有视图中原来的tags字段替换成tag_list字段。
index.html.erb

<td><%=h entry.tag_list %></td>

edit.html.erb

<%= f.text_field :tag_list %>

new.html.erb

<%= f.text_field :tag_list %>

还要将entry.rb中的验证字段tags改成tag_list。做完这些插件也就安装完成了。

既然用了插件,那么原来的tags字段就不需要了,写个迁移任务把它处理掉吧!

script/generate migration remove_tags_from_entry

迁移代码如下:

class RemoveTagsFromEntry < ActiveRecord::Migration
  def self.up
    remove_column :entries, :tags
  end

  def self.down
    add_column :entries, :tags, :string
  end
end

Related Posts

Leave a Reply

Security Code: