Ruby on Rails 3 – 序列化数组不匹配的类障碍

嘿那里,我对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 

seed.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 `' from script/rails:6:in `require' from script/rails:6:in `' 

我遇到了类似这个问题。 我的问题源于我的serialize :some_column, Array的放置serialize :some_column, Array语句。 如果在调用serialize之前有可能在ActiveRecord对象类上定义属性方法,则不会正确定义setter和getter方法。

因此,在声明哪些列被序列化之前,我会确保未在Settings类上调用define_attribute_methods

设置选项

 :null => true 

在您的字段“图”的迁移中。 它修复了这个错误