Ruby-on-rails 在数据库中存储数组:JSON 与序列化数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21312278/
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
Storing arrays in database : JSON vs. serialized array
提问by titibouboul
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.
使用 ruby-on-rails,我想存储 3 个元素的数组:帖子的最后 3 条评论。我知道我可以将 Comment 表加入到 Post 表中,但我会避免为了缩放目的而执行这个繁重的请求。
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.
所以我想知道存储这 3 个元素的最佳方式是什么,因为我想在每次发表新评论时轻松更新它们:删除最后一条评论并添加新评论。
What is the correct way to do this ? Store it in a serialized array or in a JSON object ?
这样做的正确方法是什么?将其存储在序列化数组或 JSON 对象中?
回答by DiegoSalazar
You can store Arrays and Hashes using ActiveRecord's serializedeclaration:
您可以使用 ActiveRecord 的serialize声明来存储数组和哈希:
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.
您可以指定对象类型应等于的类名(在本例中为Array)。这更明确,也更安全。您也不必在分配第一个值时创建数组,因为您将能够附加到现有(空)数组。
class Comment < ActiveRecord::Base
serialize :stuff, Array
end
comment = Comment.new # stuff: []
comment.stuff << 'some' << 'stuff' << 'as array'
You can even use a neater version called store: http://api.rubyonrails.org/classes/ActiveRecord/Store.html
您甚至可以使用更简洁的版本 store:http: //api.rubyonrails.org/classes/ActiveRecord/Store.html
This should handle your use case using a built in method.
这应该使用内置方法处理您的用例。

