序列化对象未转换

发布于 2024-11-03 12:33:28 字数 536 浏览 0 评论 0原文

我有一个名为 stats 的模型,它有一个包含 Goals (自定义类)数据的值字段

class Statistic < ActiveRecord::Base
  serialize  :value
end

当我尝试访问 goals_against (Goals 类的 atr_reader)时,我得到

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

Value 属性包含以下内容数据:

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

根据调试器采用字符串格式。

Rails 似乎不知道该数据的类型为 Goals

有人知道如何解决这个问题吗?

谢谢

I have a Model called statistics which has a value field that contains Goals (a self defined 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

金橙橙 2024-11-10 12:33:28

三件事:

首先,无论您的 Goal 类在哪里定义,请确保它已加载。在某些时候,Rails 停止自动加载 lib 文件夹中的内容。因此,无论您的额外类位于何处,请将它们设置在 config.autoload_paths (在 config/application.rb 中)中。

其次,当您将列声明为序列化时,您可以选择指定类。当您使用自定义类并且希望确保 Rails 正确执行转换时,这尤其有用。

serialize :value, Goal

第三,当您有一个序列化的列时,请确保有足够的空间。换句话说,大多数时候您希望该列在模式中是“文本”而不​​是“字符串”(否则您的 sql 引擎将默默地截断任何太大而无法放入字符串列的内容,您将最终保存了一个损坏的物体)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文