我們正在更新到較新版本的 Rails,在以前的版本中,將 object.to_json 保存到 jsonb 列會自動將其轉換為哈希。因此,我們希望從這些欄位中檢索資料作為哈希。
我們不需要使用在 jsonb 欄位中存盤字串的功能,因此我沒有挖掘成千上萬行代碼來查找每個可能的違規者,而是試圖找到可以將行為恢復到自動保存它們的位置作為哈希。
它在哪里格式化將要保存到 postgres 資料庫的資料?
uj5u.com熱心網友回復:
我的專業意見是完成專案并修復所有內容,因為如果您嘗試修復框架,任何更新都會中斷并可能撤消您可以嘗試做的任何“修復”,使其表現得像舊版本的鐵軌。
也就是說,如果您真的想深入研究 Rails 的具體細節,您可以查看以下類并覆寫/修改它們:
jsonb 映射似乎由這個檔案處理:https ://github.com/rails/rails/blob/f95c0b7e96eb36bc3efc0c5beffbb9e84ea664e4/activerecord/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb
module ActiveRecord
module ConnectionAdapters
module PostgreSQL
module OID # :nodoc:
class Jsonb < Type::Json # :nodoc:
def type
:jsonb
end
end
end
end
end
end
繼承自Type::Json.
https://github.com/rails/rails/blob/f95c0b7e96eb36bc3efc0c5beffbb9e84ea664e4/activerecord/lib/active_record/type/json.rb
module ActiveRecord
module Type
class Json < ActiveModel::Type::Value
include ActiveModel::Type::Helpers::Mutable
def type
:json
end
def deserialize(value)
return value unless value.is_a?(::String)
ActiveSupport::JSON.decode(value) rescue nil
end
def serialize(value)
ActiveSupport::JSON.encode(value) unless value.nil?
end
def changed_in_place?(raw_old_value, new_value)
deserialize(raw_old_value) != new_value
end
def accessor
ActiveRecord::Store::StringKeyedHashAccessor
end
end
end
end
看起來如果你弄亂了序列化器和反序列化器功能,你可能可以實作你想要的......但同樣,我完全不推薦這個!你將使你的代碼庫受到任何 Rails 升級的影響。自動 json 編碼和解碼可能是你搞砸了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/497371.html
