无法在rake迁移中为PG创建索引 - Rails

时间:2012-10-20 15:57:23

标签: ruby ruby-on-rails-3 rake

我正在尝试编写一个迁移,它将创建一个表并添加几个索引。

这是迁移:

class CreatePages < ActiveRecord::Migration
  def change
    create_table :pages do |t|
        t.string "name", :limit => 50
        t.string "permalink"
        t.integer "position"
        t.boolean "visible"
        t.integer "subject_id"

        add_index("pages","subject_id")
        add_index("pages","name")

      t.timestamps
    end
  end
end

当我尝试并运行此迁移时,我收到以下错误:

  

PG ::错误:错误:关系“pages”不存在   :CREATE INDEX“index_pages_on_subject_id”ON“pages”(“subject_id”)

有人能告诉我我做错了吗?

谢谢!

1 个答案:

答案 0 :(得分:4)

您需要在add_index区块之外调用create_table方法,或在区块内拨打index

第一种方法:

class CreatePages < ActiveRecord::Migration
  def change
    create_table :pages do |t|
        t.string "name", :limit => 50
        t.string "permalink"
        t.integer "position"
        t.boolean "visible"
        t.integer "subject_id"

      t.timestamps
    end

    add_index("pages","subject_id")
    add_index("pages","name")
  end
end

第二种方法:

class CreatePages < ActiveRecord::Migration
  def change
    create_table :pages do |t|
        t.string "name", :limit => 50
        t.string "permalink"
        t.integer "position"
        t.boolean "visible"
        t.integer "subject_id"
        t.index("subject_id")
        t.index("name")

      t.timestamps
    end


  end
end

我个人会选择第二个,因为这个更整洁。