使用Ruby-on-Rails,我想存储一个由3个元素组成的数组:帖子的最后3条 comments .我知道我可以将 comments 表加入到帖子1中,但是为了zoom 的目的,我会避免做这个繁重的请求.

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.

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

推荐答案

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

您可以指定对象类型应等于的类名(在本例中为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

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

Json相关问答推荐

从Json响应中为需要每个值的Post请求提取多个值

与错误相关的未定义&Quot;不是有效的JSON

如何将文件夹组织的.json文件合并为一个JSON文件,文件夹/文件名作为键

如何使用PowerShell从ExchangeOnline命令执行中获得JSON输出

Powershell ConvertFrom-Json 意外地从包含字符串的单个项目数组生成字符串而不是对象数组

导致此 Kotlin Retrofit2 错误的可能原因有哪些?

使用 Powershell,如何将 Azure AD 组成员转换为 Json 对象(文件),然后可以更新?

具有 (RegEx) 模式的 json-schema 中的枚举

为什么解析的字典相等而腌制的字典不相等?

jq搜索特定字符串并输出对应的父值

如何在 Node.js 中解析包含NaN的 JSON 字符串

使用 Javascript 判断 JSON 对象是否包含值

从 JSON 对象中删除键值对

单元测试球衣 Restful Services

json和空数组

如何在不消除对象歧义的情况下使用 circe 解码 ADT

如何在dart Flutter 中将json字符串转换为json对象?

Javascript:如何判断 AJAX 响应是否为 JSON

Java HashMap 与 JSONObject

使用 JavaScriptSerializer() 反序列化 JSON 文件