2017-06-19 26 views
1

我有一個存儲在我的數據庫的哈希類型文本的數據庫列保存和更新一列。如何當另一個改變

column_a = {sample_list: [{email: [email protected]},{email: [email protected]}]} 

我想生成包含數據庫的另一列中包含的EMAIL_ADDRESS如字符串:

column_B = "[email protected],[email protected]" 

我知道如何生成散列字符串,我的問題是什麼型號的變化我必須這樣做,只要column_A填充,column_B應該更新?

如何處理歷史數據的遷移,在這種情況下?

回答

1
class ClassName < ApplicationRecord 
    before_save :maybe_update_column_b 

    def maybe_update_column_b 
    update_column_b if column_a_changed? 
    end 

    def update_column_b 
    #your code to update column b 
    end 
end 

然後(在同一時間,你確定是安全做一個更新),在控制檯運行此。找到每個將批量的數據。

ClassName.find_each do |cn| 
    cn.update_column_b 
    cn.save 
end 
+0

我會選擇這個選項,但史蒂文應該使用類似於:'self.comlumn_b = ...',以便同一個數據庫提交保存兩列。 – fanta

+0

這就是爲什麼我使用'before_save'調用。我不知道他用什麼代碼來更新'column_b',但我會假設它會執行'self.column_b ='不是直接的db調用。並且在'before_save'調用中所做的任何更改都會保存在保存中。 –

+0

是的,你是對的。我剛剛提到,以便他知道這一點;-)。 – fanta

相關問題