使用Rails序列化来保存哈希数据库 [英] Using Rails serialize to save hash to database

查看:243
本文介绍了使用Rails序列化来保存哈希数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将哈希映射IDS保存了一些在我的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

但是,当我用钢轨控制台边做边测试:

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屋!

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