将虚拟属性添加到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
将对象转换为简化的哈希. - 然后,在
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.
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屋!