在数据库中存储数组:JSON 与序列化数组 [英] Storing arrays in database : JSON vs. serialized array

查看:50
本文介绍了在数据库中存储数组:JSON 与序列化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ruby​​-on-rails,我想存储 3 个元素的数组:帖子的最后 3 条评论.我知道我可以将 Comment 表加入到 Post 表中,但我会避免为了缩放目的而执行这个繁重的请求.

With ruby-on-rails, I want to store an array of 3 elements: the last 3 comments of a post. I know I could join the Comment table to the Post one, but I would avoid to do this heavy request for scaling purposes.

所以我想知道存储这 3 个元素的最佳方式是什么,因为我想在每次发表新评论时轻松更新它们:删除最后一条评论并添加新评论.

So I was wondering what was the best way to store those 3 elements, as I would like to update them easily every time a new comment is made: remove the last comment and add the new one.

这样做的正确方法是什么?将其存储在序列化数组或 JSON 对象中?

What is the correct way to do this ? Store it in a serialized array or in a JSON object ?

推荐答案

您可以使用 ActiveRecord 的 serialize 声明来存储数组和哈希:

You can store Arrays and Hashes using ActiveRecord's serialize declaration:

class Comment < ActiveRecord::Base
  serialize :stuff
end

comment = Comment.new  # stuff: nil
comment.stuff = ['some', 'stuff', 'as array']
comment.save
comment.stuff # => ['some', 'stuff', 'as array']

您可以指定对象类型应等于的类名(在本例中为 Array).这更明确,也更安全.您也不必在分配第一个值时创建数组,因为您将能够附加到现有(空)数组.

You can specify the class name that the object type should equal to (in this case Array). This is more explicit and a bit safer. You also won't have to create the array when you assign the first value, since you'll be able to append to the existing (empty) array.

class Comment < ActiveRecord::Base
  serialize :stuff, Array
end

comment = Comment.new  # stuff: []
comment.stuff << 'some' << 'stuff' << 'as array'

您甚至可以使用更简洁的版本 store:http://api.rubyonrails.org/classes/ActiveRecord/Store.html

You can even use a neater version called store: http://api.rubyonrails.org/classes/ActiveRecord/Store.html

这应该使用内置方法处理您的用例.

This should handle your use case using a built in method.

这篇关于在数据库中存储数组:JSON 与序列化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆