2011-11-01 22 views
0

我在我的模型serialize :vertices, Array中有一個序列化的屬性。所有似乎都可以使用它,但在重新加載控制檯(或Web請求)後,序列化數組作爲字符串返回,這顯然不是我所期望的。這裏是軌道控制檯相同的步驟:(?因爲數組在我的自定義類的可能)序列化的屬性不會回到適當的對象

ruby-1.9.2-p290 :009 > g.vertices = [Vertex.new, Vertex.new] 
=> [#<Vertex:0x000000036315e8 @neighbours={}, @options={}, @name=nil, @real_name=nil, @teacher=nil, @discipline=nil, @student_group=nil>, #<Vertex:0x00000003631458 @neighbours={}, @options={}, @name=nil, @real_name=nil, @teacher=nil, @discipline=nil, @student_group=nil>] 
ruby-1.9.2-p290 :010 > g.inspect 
=> "#<Graph id: 17, vertices: [#<Vertex:0x000000036315e8 @neighbours={}, @options={}, @name=nil, @real_name=nil, @teacher=nil, @discipline=nil, @student_group=nil>, #<Vertex:0x00000003631458 @neighbours={}, @options={}, @name=nil, @real_name=nil, @teacher=nil, @discipline=nil, @student_group=nil>], oriented: true, max_index: 0, trigger_limit: nil, created_at: \"2011-11-01 09:13:40\", updated_at: \"2011-11-01 09:17:30\", name: nil>" 
ruby-1.9.2-p290 :011 > g.save 
    (0.4ms) UPDATE "graphs" SET "vertices" = '--- 
- !ruby/object:Vertex 
neighbours: {} 
options: {} 
name: !!null 
real_name: !!null 
teacher: !!null 
discipline: !!null 
student_group: !!null 
- !ruby/object:Vertex 
neighbours: {} 
options: {} 
name: !!null 
real_name: !!null 
teacher: !!null 
discipline: !!null 
student_group: !!null 
', "updated_at" = '2011-11-01 09:21:11.516199' WHERE "graphs"."id" = 17 
=> true 
ruby-1.9.2-p290 :012 > g.inspect 
=> "#<Graph id: 17, vertices: [#<Vertex:0x000000036315e8 @neighbours={}, @options={}, @name=nil, @real_name=nil, @teacher=nil, @discipline=nil, @student_group=nil>, #<Vertex:0x00000003631458 @neighbours={}, @options={}, @name=nil, @real_name=nil, @teacher=nil, @discipline=nil, @student_group=nil>], oriented: true, max_index: 0, trigger_limit: nil, created_at: \"2011-11-01 09:13:40\", updated_at: \"2011-11-01 09:21:11\", name: nil>" 
ruby-1.9.2-p290 :013 > reload! 
Reloading... 
=> true 
ruby-1.9.2-p290 :014 > g = Graph.last 
    Graph Load (0.1ms) SELECT "graphs".* FROM "graphs" ORDER BY "graphs"."id" DESC LIMIT 1 
=> #<Graph id: 17, vertices: "---\n- !ruby/object:Vertex\n neighbours: {}\n option...", oriented: true, max_index: 0, trigger_limit: nil, created_at: "2011-11-01 09:13:40", updated_at: "2011-11-01 09:21:11", name: nil> 
ruby-1.9.2-p290 :015 > g.vertices.class 
=> String 
ruby-1.9.2-p290 :016 > 

我猜它不能正確反序列化任何提示將非常感激。謝謝。

回答

0

保存序列化的Ruby實例並不完美。我使用例如composed_of,或者實際保存的參數來構建實例到數據庫,而不是實例本身任何其他解決方案推薦一個比較正統的方法:

http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html

+0

是啊,它肯定不是最美麗的解決方案,但我不想創建數千個頂點對象,並將它們放入數據庫,如果它只用於某些計算。我還在想,爲什麼它不工作?它的古典序列化對象(如果我保存了字符串或哈希或其他通用結構,它會工作嗎?) – HouseMD