I have a hash:
我有一个哈希:
h = {
"revision"=>7,
"rev"=>"708a4bd5b",
"thumb_exists"=>false,
"bytes"=>246000,
"modified"=>"Sun, 01 Jul 2012 17:09:15 +0000",
"client_mtime"=>"Sun, 01 Jul 2012 17:09:15 +0000",
"path"=>"/Getting Started.pdf",
"is_dir"=>false,
"icon"=>"page_white_acrobat",
"root"=>"dropbox",
"mime_type"=>"application/pdf",
"size"=>"240.2 KB"
}
I would like to save it in a database with the following command: h.to_s
Then I would like to get the content from the database and to work with it as hash.
我想使用以下命令将其保存在数据库中:h.to_s然后我想从数据库中获取内容并将其作为哈希使用。
s = MyModel[:field_which_contains_hash_string]
I tried to load the content with YAML::load s
but I get an error:
我试图用YAML :: load s加载内容,但是我收到一个错误:
Psych::SyntaxError: (<unknown>): found unexpected ':' while scanning a plain scalar at line 1 column 96
I guess that's due to the colon in the time string. So what's the best way to persist the hash and retrieve it again?
我猜这是由于时间字符串中的冒号。那么持久化哈希并再次检索它的最佳方法是什么?
Help is appreciated. Best, Philip
感谢帮助。最好,菲利普
1 个解决方案
#1
13
Create a column of type text in your model. Then in your model file do
在模型中创建一个类型为文本的列。然后在你的模型文件中做
class MyModel < ActiveRecord::Base
serialize :column_name, Hash
end
Then access it using:
然后使用以下方式访
my_model = MyModel.new
my_model.column_name[:key] = value
my_model.column_name[:key]
The hash will be serialized into the column using YAML
哈希将使用YAML序列化到列中
http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html#method-i-serialize
#1
13
Create a column of type text in your model. Then in your model file do
在模型中创建一个类型为文本的列。然后在你的模型文件中做
class MyModel < ActiveRecord::Base
serialize :column_name, Hash
end
Then access it using:
然后使用以下方式访
my_model = MyModel.new
my_model.column_name[:key] = value
my_model.column_name[:key]
The hash will be serialized into the column using YAML
哈希将使用YAML序列化到列中
http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html#method-i-serialize