【发布时间】:2011-07-06 15:03:18
【问题描述】:
你好, 我对 Rails 3.0.5 和 Ruby 1.9.2 中的序列化不匹配问题感到困惑。我正在使用 Array 的子类为数据库播种,然后尝试保存到 ActiveRecord 对象。谁能帮帮我吗?我最初试图序列化为 Graph 但将其减少为 Array 以避免自定义类的错误。我很困惑,因为这对我来说没有直观的意义。非常感谢您的帮助!
class Graph < Array
..
class Settings < ActiveRecord::Base
serialize :graphs, Array
..
seeds.rb 中的最后几行——例如之后什么都没有发生。只是为了调试目的节省了很多:
sh_1g = sh_1g.to_a
d.company.settings.add_graph(sh_1g.to_a)
d.company.settings.save!
d.company.save!
d.save!
if sh_1g == d.company.settings.graphs[0]
puts "the added graph matches the first graph in the graphs array"
end
puts "added " + sh_1g.inspect + " to " + d.company.settings.graphs.inspect
puts "class of added graph as saved is" + d.company.settings.graphs[0].class.inspect
puts "class of added graph is " + sh_1g.class.inspect
puts "class of graphs serial is " + d.company.settings.graphs.class.inspect
seeds.rb 运行时的输出:
the added graph matches the first graph in the graphs array
added [[[0, 0, ..]]] to to [[[[0, 0, ..]]]..]
class of added graph as saved isArray
class of added graph is Array
class of graphs serial is Array
但是,在控制台中:
ruby-1.9.2-p180 :002 > Company.all[1].settings
ActiveRecord::SerializationTypeMismatch: graphs was supposed to be a Array, but was a String
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.5/lib/active_record/attribute_methods/read.rb:106:in `unserialize_attribute'
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.5/lib/active_record/attribute_methods/read.rb:82:in `read_attribute'
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.5/lib/active_record/base.rb:1586:in `attribute_for_inspect'
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.5/lib/active_record/base.rb:1667:in `block in inspect'
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.5/lib/active_record/base.rb:1665:in `collect'
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.5/lib/active_record/base.rb:1665:in `inspect'
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.5/lib/active_record/associations/association_proxy.rb:146:in `inspect'
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.5/lib/rails/commands/console.rb:44:in `start'
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.5/lib/rails/commands/console.rb:8:in `start'
from /Users/dlipa/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.5/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
【问题讨论】:
-
奇怪的观察——如果我从控制台运行这段代码没有问题。
标签: ruby-on-rails ruby-on-rails-3 serialization activerecord