关于rails 序列化Hash的问题

本文介绍了一种改进Rails中序列化属性的方法,通过使用typed_serialize插件可以为特定属性指定默认值,避免nil对象引发错误,并提供了安装及配置教程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Making Rails' Serialize Even Better

Rails has this handy method that allows you store almost any object in the database with ease. Most often I end up using it for storing optional attributes in a hash.

Here is the proper syntax for telling Rails that there is an options attribute that should only store Hash values.

class User < ActiveRecord::Base
  serialize :options, Hash
end

The problem

The options attribute will start off as nil, and remain nil until you set it to something else. Setting the class_name to Hash only affects what you can write to this attribute.

>> user = User.new
=> #<User id: nil, name: nil, options: nil>
>> user.options[:theme]
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
	from (irb):2
=> nil

The solution

What we really need is to automatically return an empty Hash on this new object so we can go on our merry way.

Add this to your environment.rb.

config.gem 'jqr-typed_serialize', 
  :lib => 'typed_serialize', 
  :source => 'http://gems.github.com'

Now run this command to install the gem.

$ rake gems:install

A quick change of our model will fix all of our woes.

class User < ActiveRecord::Base
  typed_serialize :options, Hash
end
>> user = User.new
=> #<User id: nil, name: nil, options: nil>
>> user.options[:theme]
=> nil
>> user.options
=> {}
我使用上面方法出现安装出现问题, 后来发现可以用 gem install typed_serialize 解决
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值