使用 Rails 序列化将哈希保存到数据库 [英] Using Rails serialize to save hash to database
问题描述
我正在尝试将哈希映射 ID 保存到我的 Rails 应用程序中的多次尝试中.我迁移到数据库以容纳这个新列:
I'm try to save a hash mapping ids to a number of attempts in my rails app. My migration to the database to accommodate this new column:
class AddMultiWrongToUser < ActiveRecord::Migration
def self.up
add_column :users, :multi_wrong, :string
end
def self.down
remove_column :users, :multi_wrong
end
end
在我的模型中,我有:
class User < ActiveRecord::Base
serialize :multi_wrong, Hash
end
但是当我使用 rails 控制台来测试时:
But when I use the rails console to test this by doing:
user = User.create()
user.multi_wrong = {"test"=>"123"}
user.save
输出为假.这里出了什么问题?
The output is false. What's going wrong here?
推荐答案
列类型错误.您应该使用文本而不是字符串.因此,您的迁移应该是:
The column type is wrong. You should use Text instead of String. Therefore, your migration should be:
def self.up
add_column :users, :multi_wrong, :text
end
然后 Rails 会为您正确地将其转换为 YAML(并执行正确的序列化).字符串字段的大小有限,只能保存特别小的值.
Then Rails will properly convert it into YAML for you (and perform proper serialization). Strings fields are limited in size and will only hold especially-small values.
这篇关于使用 Rails 序列化将哈希保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!