2015-06-24 44 views
0

我想創建一個Sequel遷移,通過列表的表,並嘗試添加一個特定的列,如果該表沒有該列尚未。續集遷移 - 只添加列,如果表還沒有它

例如:

Sequel.migration do 
    change do 
    table_list = [:table1, :table2, :table3] 

    table_list.each do |t| 
     if t does not have :specific_column yet 
     alter_table(t) do 
      add_column :sepcific_column, type: String 
     end 
     end 
    end 
    end 
end 

是否可以告訴我們,如果列一個表中已經存在,所以我可以做相應的東西?

回答

1

是的,這是可能的。方法Dataset#columns返回一列列表。可以使用此結果與include?

完整的示例進行檢查:

Sequel.migration do 
    change do 
    table_list = [:table1, :table2, :table3] 

    table_list.each do |t| 
     if ! self[t].columns.include?(:specific_column) 
     alter_table(t) do 
      add_column :specific_column, type: String 
     end 
     end 
    end 
    end 
end 

Sequel.migration do 
    change do 
    table_list = [:table1, :table2, :table3] 

    table_list.each do |t| 
     alter_table(t) do 
      add_column :specific_column, type: String 
     end unless self[t].columns.include?(:specific_column) 
     end 
    end 
    end 
end 
+0

甜,你一定意味'除非自[T] ...'哈哈,但它的工作就像一個魅力。謝謝您的幫助! – Edward

+0

你是對的,只是另一種方式;)我會調整答案。 – knut