将虚拟属性添加到 json 输出 [英] Add virtual attribute to json output
问题描述
假设我有一个处理待办事项列表的应用程序.清单有已完成和未完成的项目.现在我想向列表对象添加两个虚拟属性;列表中已完成和未完成项目的数量.我还需要将这些显示在 json 输出中.
Let's say I have an app that handles a TODO list. The list has finished and unfinished items. Now I want to add two virtual attributes to the list object; the count of finished and unfinished items in the list. I also need these to be displayed in the json output.
我的模型中有两种方法可以获取未完成/已完成的项目:
I have two methods in my model which fetches the unfinished/finished items:
def unfinished_items
self.items.where("status = ?", false)
end
def finished_items
self.items.where("status = ?", true)
end
那么,如何在我的 json 输出中获取这两种方法的数量?
So, how can I get the count of these two methods in my json output?
我使用的是 Rails 3.1
I'm using Rails 3.1
推荐答案
Rails中对象的序列化有两个步骤:
The serialization of objects in Rails has two steps:
- 首先,调用
as_json
将对象转换为简化的 Hash. - 然后,在
as_json
返回值上调用to_json
以获得最终的 JSON 字符串.
- First,
as_json
is called to convert the object to a simplified Hash. - Then,
to_json
is called on theas_json
return value to get the final JSON string.
您通常希望单独保留 to_json
,因此您需要做的就是添加 你自己的as_json
实现 有点像这样:
You generally want to leave to_json
alone so all you need to do is add your own as_json
implementation sort of like this:
def as_json(options = { })
# just in case someone says as_json(nil) and bypasses
# our default...
super((options || { }).merge({
:methods => [:finished_items, :unfinished_items]
}))
end
你也可以这样做:
def as_json(options = { })
h = super(options)
h[:finished] = finished_items
h[:unfinished] = unfinished_items
h
end
如果您想为方法支持的值使用不同的名称.
if you wanted to use different names for the method-backed values.
如果您关心 XML 和 JSON,请查看 serializable_hash代码>
.
If you care about XML and JSON, have a look at serializable_hash
.
这篇关于将虚拟属性添加到 json 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!