2015-06-16 37 views
0
class UpdateIndexOnUsers < ActiveRecord::Migration 
    def change 
    sql = 'DROP INDEX index_users_on_email' 
    sql << ' ON users' if Rails.env == 'production' # Heroku pg 
    ActiveRecord::Base.connection.execute(sql) 
    end 
end 

有沒有辦法通過一次遷移而不是回滾來改變這種情況?Rails如何恢復遷移更改?

編輯:試圖rake db:migrate:down VERSION=20150611173755,但沒有奏效。

PG::UndefinedObject: ERROR: index "index_users_on_email" does not exist 
: DROP INDEX index_users_on_email/Users/goda/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec' 
/Users/tingaloo/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `block in execute' 
/Users/tingaloo/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:466:in `block in log' 
/Users/tingaloo/.rvm/gems/[email protected]/gems/activesupport-4.2.0/lib/active_support/notifications/instrumenter.rb:20:in `instrument' 
/Users/tingaloo/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:460:in `log' 
/Users/tingaloo/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:154:in `execute' 
/Users/tingaloo/rails/novelshare/db/migrate/20150611173755_update_index_on_users.rb:5:in `change' 

回答

0

定製SQL不reverisble。

但你可以改變它是:

def up 
    sql = 'DROP INDEX index_users_on_email' 
    sql << ' ON users' if Rails.env == 'production' # Heroku pg 
    ActiveRecord::Base.connection.execute(sql) 
end 

def down 
    ** code to add the index back ** 
end 

但我認爲你應該使用Rails的語法:

def up 
    remove_index :users, :email if Rails.env == 'production' 
end 

def down 
    add_index :users, :email 
end 
+0

我試圖底部的代碼,但沒有奏效。我不確定最上面的代碼是做什麼的。 – goda

+0

可能是您的索引'index_users_on_email'的命名可能與'add_index'和'remove_index'的約定名稱不同。 – davidwessman