Rails - 从控制台访问序列化数据 [英] Rails - Accessing serialized data from console
问题描述
由于某种原因,每当我从控制台访问序列化属性时,它会将其视为正常字符串。当不从控制台访问(例如从视图)时,序列化/反序列化工作正常。我有如下代码:
For some reason, whenever I access a serialized attribute from the console, it treats it as a normal string. The serialization/deserialization works fine when not accessed from the console (ex. from the view). I have the code as follows:
class Foo < ActiveRecord::Base
belongs_to :user
serialize :serialized_data # column type is text
...
end
例如,如果我要在 app / views / users / show.html.erb
中插入以下内容:
For example, if I were to put in app/views/users/show.html.erb
the following:
<%= @user.foo.serialized_data.first %>
它会正确地打印出第一组数据。当我从控制台运行以下命令时:
It would properly print out the first of the set of data. When I run the following command from console:
> User.first.foo.serialized_data.first
它只是打印出
,这是YAML文件的第一个字符。此外, User.first.foo.serialized_data
将打印一个大字符串,而不是最初保存的数组/散列。
It would simply print out -
, which is the first character of a YAML file. Further, User.first.foo.serialized_data
would print out a large string rather than the array/hash that was originally saved.
UPDATE:
如果我在:serialized_data
中生成数据,并尝试在同一个控制台会话中访问它,它似乎工作得很好。一旦我关闭控制台,然后重新输入,就会出现问题。
UPDATE:
If I generate the data in :serialized_data
and attempt to access it in the same console session, it seems to work fine. Once I close console and then re-enter it, the issue occurs.
编辑:
要澄清,:serialized_data
是以下形式的散列数组:
For clarification, :serialized_data
is an array of hashes in the following form:
[{"stuff" => {"name" => name, "qty" => 1}}, {"stuff" => {"name" => name2, "qty" => 3}}]
,可以这样访问:
user.foo.serialized_data[0]["stuff"]["qty"]
=> 1
编辑2:
还有一点很重要,在我的哈希中存储模型对象。如下面的注释中提到的,如果我们使用我给的例子, user.foo.serialized_data [0] [stuff] [name]
具有属性的模型 Name
的对象。所以,我可以运行 user.foo.serialize_data [0] [stuff] [name]。id
等等。可能对象是乱七八糟的YAML文件的语法。
EDIT 2:
It may also be important to note that I am storing a model object in my hash. As mentioned in the comments below, if we were to use the example I gave, user.foo.serialized_data[0]["stuff"]["name"]
would return an object of model Name
with attributes. So, I could run user.foo.serialize_data[0]["stuff"]["name"].id
and so on. Maybe the object is messing with the syntax of the YAML file.
推荐答案
问题是我存储一个整个对象在切换到对象 id
,修复了这个问题。
The problem was that I was storing an entire object in the hash value, as mentioned in EDIT 2. Switching it to the object id
fixed this issue.
这篇关于Rails - 从控制台访问序列化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!