序列化属性不会作为正确的对象返回

时间:2011-11-01 09:33:55

标签: ruby ruby-on-rails-3 serialization deserialization

我的模型serialize :vertices, Array中有序列化属性。在使用它时,一切似乎都没问题,但在我重新加载控制台(或在Web请求上)后,序列化数组将作为字符串返回,这显然不是我所期望的。以下是rails控制台中的相同过程:

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 > 

我猜它没有正确反序列化(也许是因为我在数组中的自定义类?)任何提示都会非常感激。感谢。

1 个答案:

答案 0 :(得分:0)

保存序列化的Ruby实例并不是很优雅。我建议使用更正统的方法,例如使用composed_of或任何其他解决方案实际保存参数以将实例构建到数据库而不是实例本身:

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