在数据库中存储数组:JSON与序列化数组

我想存储一个由3个元素组成的数组:最后3个post的评论。 我知道我可以将评论表join到Post 1,但是我会避免这样做。

所以我想知道存储这3个元素的最佳方法是什么,因为每次发表新的评论时,我都会很容易地更新它们:删除最后的评论并添加新的评论。

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

您可以使用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'] 

你可以指定对象types应该等于的类名(在这个例子中是Array )。 这更明确,更安全。 当您分配第一个值时,您也不必创build数组,因为您可以追加到现有的(空)数组。

 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

这应该使用内置的方法来处理你的用例。