Rails:如何处理“属性应该是数组,但是是字符串”。错误? [英] Rails: How to handle "Attribute was supposed to be a Array, but was a String" error?

查看:86
本文介绍了Rails:如何处理“属性应该是数组,但是是字符串”。错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表,其中一栏是文本类型。
其中有一个小字符串,应将其序列化为数组

I have a table with one column that is of text type. There's a small string in it that should be serialized as an array

serialize :image_urls, Array 

有时候,SQL插入数据的速度更快。
在这种情况下,我以字符串形式进行插入

There are times when SQL is just faster for inserting data. When this is the case, I do the insert as a string

["image1.jpg", "image2.jpg"]

由于我在插入字符串时,Rails应用程序在尝试读取字符串时会崩溃数据,并显示以下错误消息:

Since I'm inserting a string my Rails app crashes when it tries to read the data, with the following error message:

Attribute was supposed to be a Array, but was a String

有没有办法避免抛出此错误,或者捕获并转换数据?

我的意思是将字符串转换为数组只是一个简单的调用,因此,这应该很容易。我只是不知道在哪里或如何实现。



我认为可以覆盖object_from_yaml,但是我不确定在哪里进行这项工作。

我在正确的轨道上吗?

I mean converting the string to an array is just a simple call, so, this should be easy. I just don't know where, or how to accomplish it.


I sort of think overriding object_from_yaml, but I'm not sure where to do this work.
Am I in the right track?

推荐答案

来自精读手册


serialize (attr_name,class_name = Object)

[...]序列化是通过YAML完成的。

serialize(attr_name, class_name = Object)
[...] The serialization is done through YAML.

因此,该列应包含 image_urls '[ image1 .jpg, image2.jpg]'不是YAML数组。如果您想处理原始序列化数据,则应该使用类似

So the column should contain a YAMLized version of your image_urls but '["image1.jpg", "image2.jpg"]' is not a YAML array. If you want to muck around with the raw serialized data then you should use something like

["image1.jpg", "image2.jpg"].to_yaml
# ---------------------------^^^^^^^

生成字符串。

或者更好的是,停止使用 serialize 完全支持一个单独的表。

Or better, stop using serialize altogether in favor of a separate table.

这篇关于Rails:如何处理“属性应该是数组,但是是字符串”。错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆