Rails: How to handle “Attribute was supposed to be a Array, but was a String” error?

左心房为你撑大大i 提交于 2019-12-08 15:28:57

问题


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 

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"]

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

Is there a way to not have this error thrown, or to catch it and convert the data?

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?

回答1:


From the fine manual:

serialize(attr_name, class_name = Object)
[...] The serialization is done through 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
# ---------------------------^^^^^^^

to generate the string.

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




回答2:


In Rails 4 it worked for me without any .to_yaml, just added it to strong params as image_urls: []




回答3:


you can try like this: {:serialized_attribute_name => [ ]}. And don't forget to add this in appropriate controller as strong parameters. It helps me when I was suffering from same problem.



来源:https://stackoverflow.com/questions/10273301/rails-how-to-handle-attribute-was-supposed-to-be-a-array-but-was-a-string-er

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!