Rails 3 - How to Create a JSON Object to store in the database

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

I'm creating an AuditLog observer that watches over several models.

I'd like the observer to have an after_create, which creates a JSON object that is stored in a database column. It will contain data like {photoid:123, photoname: "asdasd", creator_id: "asdasd"} etc...

In Rails, how do I create this type of JSON object and then how do I insert it into the DB along with other non-JSON fields?

Thanks

回答1:

Current versions of rails support json serialisation out of the box. Define your field as a string (or text) in the migration and then:

class Foo < ActiveRecord::Base   serialize :field, JSON end  bar = Foo.new bar.field = [1,2,3] bar.save 


回答2:

First, definitely check out ActiveRecord serialize and see if it does what you need: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-serialize

However, if you need JSON specifically (serialize uses YAML by default), then you can always fake it by hand.

You can simply build a hash in Ruby and then call to_json on it before assigning it to your model attribute.

data = { 'photoid' => 123, 'photoname' => "asdasd", 'creator_id' => "asdasd" } myrecord.stored_data = data.to_json myrecord.save 


回答3:

Take a look at this: http://github.com/laserlemon/vestal_versions

If it's not what you're looking for, it will at least show you it's done.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!