如何在.to_json方法上获取自定义属性? [英] How to get custom attributes on .to_json method?
问题描述
例如,我有这个模型:
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屋!