2013-11-04 21 views
2

我看過Rails指南和Rails API,我無法理解可逆和恢復的用法。在Active Record遷移中可逆並恢復

因此,例如,在這裏看到http://guides.rubyonrails.org/migrations.html#using-reversible相連,包括下面的例子:\

它說 Complex migrations may require processing that Active Record doesn't know how to reverse. You can use reversible to specify what to do when running a migration what else to do when reverting it. For example,

class ExampleMigration < ActiveRecord::Migration 
    def change 
    create_table :products do |t| 
     t.references :category 
    end 

reversible do |dir| 
    dir.up do 
    #add a foreign key 
    execute <<-SQL 
     ALTER TABLE products 
     ADD CONSTRAINT fk_products_categories 
     FOREIGN KEY (category_id) 
     REFERENCES categories(id) 
    SQL 
    end 
    dir.down do 
    execute <<-SQL 
     ALTER TABLE products 
     DROP FOREIGN KEY fk_products_categories 
    SQL 
    end 
end 

add_column :users, :home_page_url, :string 
rename_column :users, :email, :email_address 
end 

我得到的是,在下跌段的代碼是什麼將回滾運行,但爲什麼在上面的代碼塊中包含代碼?我還看到另一個例子,其中只有一個上塊的可逆部分。這樣的代碼的目的是什麼?最後我不明白revert。下面是Rails指南中包含的例子,但對我來說沒什麼意義。

`The revert method also accepts a block of instructions to reverse. This could be useful to revert selected parts of previous migrations. For example, let's imagine that ExampleMigration is committed and it is later decided it would be best to serialize the product list instead. One could write: 
class SerializeProductListMigration < ActiveRecord::Migration 
    def change 
    add_column :categories, :product_list 


reversible do |dir| 
     dir.up do 
     # transfer data from Products to Category#product_list 
     end 
     dir.down do 
     # create Products from Category#product_list 
     end 
    end 

    revert do 
     # copy-pasted code from ExampleMigration 
     create_table :products do |t| 
     t.references :category 
     end 

     reversible do |dir| 
     dir.up do 
      #add a foreign key 
      execute <<-SQL 
      ALTER TABLE products 
       ADD CONSTRAINT fk_products_categories 
       FOREIGN KEY (category_id) 
       REFERENCES categories(id) 
      SQL 
     end 
     dir.down do 
      execute <<-SQL 
      ALTER TABLE products 
       DROP FOREIGN KEY fk_products_categories 
      SQL 
     end 
     end 

     # The rest of the migration was ok 
    end 
    end 
end` 

回答

1

我不以任何方式在這方面的專家,但我從閱讀理解指南是:

reversible調用在第一個例子表達的四個組成部分的第二change遷移。 (注意:你所擁有的縮進在這方面具有誤導性,應該更新以符合指南。)它與其他組件有關,但與其他組件不同,因此它有一個updown部分。我無法解釋你爲什麼只有一個方向而不是另一個方向reversible,正如你所表示的那樣。

revert調用告訴系統通過名稱或提供描述(正向)遷移的塊來恢復先前的遷移。你表現的例子是後一種情況下,我想通過它後面的指南中的段落仔細閱讀是最好的理解,即:

相同的遷移也已被寫入,而無需使用恢復 但這可能會涉及更多的步驟:顛倒create_table和reversible的順序,用drop_table替換create_table,並最終替換掉down,反之亦然。這一切都由恢復。

+0

無論如何,我想軌道指南對於新手來說太簡單了。非常感謝您的幫助。 – macsplean