Re: [問題] 關於 rails 的 from_json / to_json
※ 引述《suomax (shadow)》之銘言:
: 環境:
: Rails 2.1.0
: Rails 有兩個 from_json / to_json 函式,我想利用這兩個函式將一個
: 物件陣列存在資料庫中,但是搞不太清楚它們的使用方式。
這東西是放在 ActiveRecord::Serialization 中,其中又用到 attribute_names,
我懶得繼續追蹤下去,rails 內部是一團東西卡在一起,要這樣拆開用,
要花一點時間研究。
: 我有一個 class:
: class Foo
: attr_accessor :value
: def initialize(v)
: @value = v
: end
: end
也就是說你這個 Foo 單是 include ActiveRecord::Serialization 是不行的,
剛剛試了一下,會欠 attribute_names, 從哪來的我懶得追蹤了。
也許你直接繼承 ActiceRecord::Base 會單純些...
而這邊完全沒有 include / extend / 繼承是不能跑的。
有趣的是,單這樣寫,to_json 是能動的。但是我看 from_json 需要
attributes= 這個 method, 幫他定義上去之後,to_json 就會爛掉...
同樣我也懶得追蹤原因了...
: foo_arr = Array.new
: foo_arr << Foo.new(1)
: foo_arr << Foo.new(2)
: foo_json = foo_arr.to_json
: # => "[{\"value\": 1}, {\"value\": 2}]"
: 如果我想把 foo_json 重現回一個 Foo Arry, 要怎麼做呢?
: 謝謝 m(_ _)m
基本上這應該是辦不到的,因為 json 裡面沒有 Foo 的資訊,
他不會知道你要把 json 轉成什麼?
假使你的 Foo 繼承 ActiveRecord::Base 好了(你的例子裡沒有),
那麼你可以寫成像這樣:
ActiveSupport::JSON.decode(foo_json).inject([]){ |result, foo_attrs|
result << Foo.new(foo_attrs)
}
但如果你的 Foo 不需要繼承 ActiveRecord::Base, 那你大概有三條路可以走:
1. 想辦法利用 ActiveRecord::Serialization, 那就要去看 rails 內部
一團混亂的 source code. 根據我的經驗,這很難搞,他內部糾結狀況很嚴重。
2. 自己重作 serialization 吧,沒有複雜結構的話,這不難寫。
3. 改用 Marshal + Base64 存到 text 欄位中。我看到的 binary 都是這樣存的。
不知道單用 Marshal 存到 blob 裡面行不行?我資料庫不熟。
一般而言我會建議 3, 比較省事...
--
Nobody can take anything away from him.
Nor can anyone give anything to him.
What came from the sea,
has returned to the sea.
Chrono Cross
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.135.28.18
推
10/01 17:13, , 1F
10/01 17:13, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):
Ruby 近期熱門文章
PTT數位生活區 即時熱門文章