2017-08-03 42 views
0

我正在將rails 4.2應用程序升級到rails 5.其中一個模型使用ActiveRecord :: Store。升級後檢索記錄時,該商店只返回一個空的散列。我不知道爲什麼會發生這種情況,並且無法在變更日誌中找到任何內容。所以任何幫助和解釋將不勝感激。Activerecord商店只在rails 5升級後返回空散列

這裏的鐵軌輸出4控制檯:

=> #<StoredDataQuery ..., config: {"start_date"=>6, "end_date"=>0, ...>

和軌道5:

=> #<StoredDataQuery ..., config: {}, ...

的psql輸出:

development=# SELECT config FROM stored_data_queries WHERE id=1; 
        config 
--------------------------------------------- 
--- !ruby/hash:ActionController::Parameters+ 
start_date: 6        + 
end_date: 0        + 
interval: day        + 

(1 row) 

縱觀SQL輸出,我懷疑它有som數據被序列化爲ActionController::Parameters

感謝您的幫助!

+0

更新:經過幾次實驗後,我發現rails 5將對象存儲爲'ActiveSupport :: HashWithIndifferentAccess'。所以現在的問題是,是否有比原始sql更好的方式來轉換存儲的對象。 –

+0

這裏是如何解決它在sql(postgres)'UPDATE stored_data_queries SET config = replace(config,'ActionController :: Parameters','ActiveSupport :: HashWithIndifferentAccess');' –

回答

0

在將Rails 4.2升級到Rails 5.0之後,將Zammad升級到此處之後也是如此。經過一番研究後,我發現活動記錄只是從商店中讀取ActiveSupport :: HashWithIndifferentAccess(其他類被跳過)。

因此,對於遷移,您可以在遷移中覆蓋ActiveRecord::Store::IndifferentCoder.as_indifferent_hash,從數據庫中讀取所有相關記錄並將其保存回去(然後將所有ActionController :: Parameters轉換爲ActiveSupport :: HashWithIndifferentAccess)。

對於我來說,下面的遷移(下導軌5.0)一直致力於所有的ActionController ::參數轉換成的ActiveSupport :: HashWithIndifferentAccess:

require 'active_record/store' 
module ActiveRecord 
    module Store 
    class IndifferentCoder 
     def self.as_indifferent_hash(obj) 
     case obj 
     # re-enable using ActionController::Parameters in stores, 
     # convert them to ActiveSupport::HashWithIndifferentAccess 
     # at reading from db 
     when ActionController::Parameters 
      obj.permit!.to_h 
     # /re-enable 
     when ActiveSupport::HashWithIndifferentAccess 
      obj 
     when Hash 
      obj.with_indifferent_access 
     else 
      ActiveSupport::HashWithIndifferentAccess.new 
     end 
     end 
    end 
    end 
end 

class FixedStoreUpgrade45 < ActiveRecord::Migration[5.0] 
    def up 
    [Macro, Taskbar, Calendar, Trigger, Channel, Job, PostmasterFilter, Report::Profile, Setting, Sla, Template].each do |class_name| 
     class_name.all.each do |record| 
     begin 
      record.save! 
     rescue => e 
      Rails.logger.error "Unable to save/update #{class_name}.find(#{record.id}): #{e.message}" 
     end 
     end 
    end 
    end 
end 
0

這裏是如何解決它的SQL(Postgres的):

UPDATE stored_data_queries SET config = replace(config, 'ActionController::Parameters', 'ActiveSupport::HashWithIndifferentAccess');

相關問題