将虚拟属性添加到json输出 [英] Add virtual attribute to json output

查看:124
本文介绍了将虚拟属性添加到json输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个处理待办事项清单的应用程序.清单中已完成和未完成的项目.现在,我想向列表对象添加两个虚拟属性.列表中已完成和未完成项目的计数.我还需要将这些显示在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 the as_json return value to get the final JSON string.

您通常希望不打扰to_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆