简体   繁体   English

Rails 3 - 如何创建要存储在数据库中的JSON对象

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

I'm creating an AuditLog observer that watches over several models. 我正在创建一个审核多个模型的AuditLog观察器。

I'd like the observer to have an after_create, which creates a JSON object that is stored in a database column. 我希望观察者有一个after_create,它创建一个存储在数据库列中的JSON对象。 It will contain data like {photoid:123, photoname: "asdasd", creator_id: "asdasd"} etc... 它将包含{photoid:123,photoname:“asdasd”,creator_id:“asdasd”}等数据...

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对象,然后如何将其与其他非JSON字段一起插入到数据库中?

Thanks 谢谢

Current versions of rails support json serialisation out of the box. 当前版本的rails支持开箱即用的json序列化。 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

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 首先,一定要查看ActiveRecord序列化并查看它是否符合您的要求: 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. 但是,如果你需要专门的JSON(序列化默认使用YAML),那么你总是可以手工伪造它。

You can simply build a hash in Ruby and then call to_json on it before assigning it to your model attribute. 你可以简单地在Ruby中构建一个哈希,然后在将它分配给你的模型属性之前调用它to_json

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

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

If it's not what you're looking for, it will at least show you it's done. 如果它不是你想要的,它至少会告诉你它已经完成了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM