如何在.to_json方法上获取自定义属性? [英] How to get custom attributes on .to_json method?

查看:101
本文介绍了如何在.to_json方法上获取自定义属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有这个模型:

class User < ActiveRecord::Base

  def foo
    bar
  end

end

当我这样做时: <%= User.all.to_json%>

When i do this: <%= User.all.to_json %>

我明白了:

[{"user":{"created_at":"2011-06-07T17:40:21-03:00","login":"abcd","password":"1234","updated_at": "2011-06-07T18:10:04-03:00"}}]

[{"user":{"created_at":"2011-06-07T17:40:21-03:00","login":"abcd", "password":"1234","updated_at":"2011-06-07T18:10:04-03:00"}}]

我如何也可以在此json上获取foo?另外,foo也是一个activerecord..

How can i get foo on this json too? Also, foo is an activerecord too..

谢谢

推荐答案

User.all.to_json(:methods => :foo)

限制发送的属性可能也很有用,您可以使用:only:except选项执行此操作.例如您不太可能需要此数据中的密码.

It may also be useful to limit the attributes that are sent, you can do this with either the :only and :except options. e.g. It is unlikely you will want the password in this data.

这篇关于如何在.to_json方法上获取自定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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