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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3835015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:17:37  来源:igfitidea点击:

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

ruby-on-railsjsonruby-on-rails-3

提问by AnApprentice

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. It will contain data like {photoid:123, photoname: "asdasd", creator_id: "asdasd"} etc...

我希望观察者有一个 after_create,它创建一个存储在数据库列中的 JSON 对象。它将包含像 {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

谢谢

回答by Matt Connolly

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

当前版本的 rails 支持开箱即用的 json 序列化。在迁移中将您的字段定义为字符串(或文本),然后:

class Foo < ActiveRecord::Base
  serialize :field, JSON
end

bar = Foo.new
bar.field = [1,2,3]
bar.save

回答by tfe

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_jsonon 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

回答by Coderama

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.

如果这不是你要找的,它至少会告诉你它已经完成了。