Rails 3,我添加了一个表,然后添加了一个列,现在我想添加一个索引

In Rails 3,

I created a table with a migration, then added a column with a migration which creates a has_many, belongs_to relationship....

I then ran rake db:migrate

I'd like to now add an Index because I forgot to add it before I can migrate. can I add that to one of the existing migration files (the create table one) or do I need to create a new migration for adding an index to an existing table?

Thanks

#0

I usually create a new migration if I forget something like that (especially if I have already migrated in production). But if you are still in development, then you can alter your last migration file and use the redo rake command:

rake db:migrate:redo

There is also:

rake db:rollback  # Rolls the schema back to the previous version (specify steps w/ STEP=n).

Run this command to view all the different rake tasks:

rake -T db

Here is the section in the Rails Guide that talks about it: http://guides.rubyonrails.org/migrations.html#rolling-back

#1

If you would like to add your index without losing the data, you must create a new migration to add an index. Assuming your model is called Widget and the foreign model is called Zidget;

rails generate migration AddIndexToWidgets

and inside your new migration file at db/migrate/xxxxxxxxxx_add_index_to_widgets

class AddIndexToWidgets < ActiveRecord::Migration
  def self.up
    change_table :widgets do |t|
      t.index :zidget_id # add ':unique => true' option if necessary
    end
  end

  def self.down
    change_table :widgets do |t|
      t.remove_index :zidget_id
    end
  end
end 

and then rake db:migrate as usual and voilà, you have your indexed column.


Update: If adding an index is all you're doing, there is a more concise way to write the same thing. There is no difference regarding the results. It's just that the former syntax is meant to DRY your code if you have more than one change for your table.

class AddIndexToWidgets < ActiveRecord::Migration
  def self.up
    add_index :widgets, :zidget_id # add ':unique => true' option if necessary
  end

  def self.down
    remove_index :widgets, :column => :zidget_id
  end
end 

推荐文章

如何知道哪些属性存储在ControlState中,哪些存储在ViewState中?

如何知道哪些属性存储在ControlState中,哪些存储在ViewState中?

推荐文章

Gitlab操作手册

Gitlab操作手册

推荐文章

Django模型覆盖保存/使用信号/或使用模型窗体?

Django模型覆盖保存/使用信号/或使用模型窗体?

推荐文章

ASP.NET Ajax-自动完成编辑器控件显示在其他控件后面

ASP.NET Ajax-自动完成编辑器控件显示在其他控件后面

推荐文章

Tomcat如何实现Comet

Tomcat如何实现Comet

推荐文章

HTTP的隐藏特性

HTTP的隐藏特性

推荐文章

Django admin管理界面,管理界面变成中文,管理界面显示所有表,表名改成中文名

Django admin管理界面,管理界面变成中文,管理界面显示所有表,表名改成中文名

推荐文章

CouchDB的视图有问题

CouchDB的视图有问题

推荐文章

浏览SSAS多维数据集时Excel中的会计年度

浏览SSAS多维数据集时Excel中的会计年度

推荐文章

ajax向后台传递参数-动态组织json串

ajax向后台传递参数-动态组织json串

推荐文章

通过Ajax刷新表列

通过Ajax刷新表列

推荐文章

typescript中类的继承

typescript中类的继承

推荐文章

如何使用MAMP从命令行运行PHP脚本?

如何使用MAMP从命令行运行PHP脚本?

推荐文章

依赖注入和控制反转术语

依赖注入和控制反转术语

推荐文章

jquery实现ajax传递

jquery实现ajax传递

推荐文章

13,SQLAlchemy 增删改查 一对多 多对多

13,SQLAlchemy 增删改查 一对多 多对多