Rails 3-如何创建一个JSON对象存储在数据库中 [英] Rails 3 - How to Create a JSON Object to store in the database
问题描述
我正在创建一个AuditLog观察器,用于监视多个模型.
I'm creating an AuditLog observer that watches over several models.
我希望观察者具有一个after_create,它创建一个存储在数据库列中的JSON对象.它将包含{photoid:123,photoname:"asdasd",creator_id:"asdasd"}等数据……
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...
在Rails中,如何创建这种JSON对象,然后将其与其他非JSON字段一起插入数据库?
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?
谢谢
推荐答案
当前版本的rails支持开箱即用的json序列化.在迁移中将您的字段定义为字符串(或文本),然后:
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
这篇关于Rails 3-如何创建一个JSON对象存储在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!