How to get custom attributes using .to_json method?

For example, I have this model:

class User < ActiveRecord::Base

  def foo
    bar
  end

end

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

I get this:

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

How can i get foo on this json? In addition, foo is also activerecord ..

thank

+3
source share
1 answer
User.all.to_json(:methods => :foo)

It may also be useful to limit sent attributes, you can do this with the :onlyand options :except. For example, it is unlikely that you will need a password in this data.

+3

All Articles