开发者

serialized object not being converted

I have a Model called statistics which has a value field that contains Goals (a self d开发者_高级运维efined class) data

class Statistic < ActiveRecord::Base
  serialize  :value
end

When I try to access the goals_against (an atr_reader of the Goals class) I get

undefined method `goals_against' for #<String:0x54f8400>

The value property contains following data:

--- !ruby/object:Goals \ngoals: {}\n\ngoals_against: 1\ngoals_for: 0\nversion: 1\n

In string format according to the debugger.

It seems that rails doesn't know this data is of type Goals.

Someone knows how to solve this?

Thanks


Three things:

First, where ever your Goal class is defined, make sure it is loaded. At some point Rails stopped auto-loading stuff in the lib folder. So where ever your extra classes are located, set them in config.autoload_paths (in config/application.rb).

Second, when you declare a column as serialized, you have the option of specifying the class. This is especially useful when you are working with a custom class and you want to make sure Rails does the conversion correctly.

serialize :value, Goal

Third, when you have a column that is serialized, make sure you have enough room for it. In other words, most of the time you're going to want that column to be "text" and not "string" in your schema (otherwise your sql engine will silently truncate anything too large to fit in a string column and you'll end up saving a broken object).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜