我有一个使用序列化列模型:
I have a model that uses a serialized column:
class Form < ActiveRecord::Base
serialize :options, Hash
end
有没有一种方法,使该序列化使用JSON代替YAML?
Is there a way to make this serialization use JSON instead of YAML?
更新
请参阅下面的一个更合适的Rails> = 3.1的答案中旬的高额定答案。这是Rails的℃的伟大的答案; 3.1。
See mid's high rated answer below for a much more appropriate Rails >= 3.1 answer. This is a great answer for Rails < 3.1.
也许这就是你要找的内容。
Probably this is what you're looking for.
Form.find(:first).to_json
更新
1)安装JSON宝石:
gem install json
2)创建JsonWrapper类
2) Create JsonWrapper class
# lib/json_wrapper.rb
require 'json'
class JsonWrapper
def initialize(attribute)
@attribute = attribute.to_s
end
def before_save(record)
record.send("#{@attribute}=", JsonWrapper.encrypt(record.send("#{@attribute}")))
end
def after_save(record)
record.send("#{@attribute}=", JsonWrapper.decrypt(record.send("#{@attribute}")))
end
def self.encrypt(value)
value.to_json
end
def self.decrypt(value)
JSON.parse(value) rescue value
end
end
3)加入模型回调:
3) Add model callbacks:
#app/models/user.rb
class User < ActiveRecord::Base
before_save JsonWrapper.new( :name )
after_save JsonWrapper.new( :name )
def after_find
self.name = JsonWrapper.decrypt self.name
end
end
4)测试一下吧!
4) Test it!
User.create :name => {"a"=>"b", "c"=>["d", "e"]}
这不是很干,但我尽力了。如果任何人都可以修复 after_find
在用户
模式,这将是巨大的。
It's not quite DRY, but I did my best. If anyone can fix after_find
in User
model, it'll be great.
上一篇:上创建的ActiveRecord的重写ID重写、ActiveRecord、ID
下一篇:在轨道4 uniq的:通过:使用的has_many时,德precation警告轨道、uniq、precation、has_many