[英]How to get custom attributes on .to_json method?
例如,我有這個 model:
class User < ActiveRecord::Base
def foo
bar
end
end
當我這樣做時:<%= 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"}}]
我怎樣才能在這個 json 上獲得 foo 呢? 此外, foo 也是一個 activerecord ..
謝謝
User.all.to_json(:methods => :foo)
限制發送的屬性也可能很有用,您可以使用:only
和:except
選項來做到這一點。 例如,您不太可能需要此數據中的密碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.