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

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

问题描述

我要存储3个元素的数组:一个帖子的最后3条评论。我知道我可以加入注释表后,但我会避免换算目的做这个沉重的要求。

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的连载声明:

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']

您可以指定类名,对象类型应该等于(在这种情况下,阵列)。这更加明确和更加安全。你也不必在指定的第一个值来创建磁盘阵列,因为你可以附加到现有的(空)阵列。

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'

您甚至可以使用一个更简洁的版本,称为店:<一href=\"http://api.rubyonrails.org/classes/ActiveRecord/Store.html\">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天全站免登陆