How to customize to_json response in Rails 3?

You can override as_json in your model. Something like: class Post Images, # then do the same `as_json` method for Image foo: self. Really_cool_method } end end And Rails takes care of the rest when using respond_with not entirely sure what options gets set to, but probably the options you give to respond_with ( :include :only and so on).

You can override as_json in your model. Something like: class Post Images, # then do the same `as_json` method for Image foo: self. Really_cool_method } end end And Rails takes care of the rest when using respond_with.

Not entirely sure what options gets set to, but probably the options you give to respond_with (:include, :only and so on).

He wants to change as_json, as_xml, as_foobar all in one place. – scragz Apr 2 at 20:38 Yeah, this isn't really DRY – coneybeare Sep 13 at 15:35.

It is not the rails 3 built-in way, but I found a great gem that is actively maintained on Rails 3: acts_as_api.

1 This link is a 404. – lashleigh Jan 16 at 2:31 1 github. Com/fabrik42/acts_as_api – coneybeare Jan 16 at 19:55.

Probably too late, but I found a more DRY solution digging through the rails docs. This works in my brief tests, but may need some tweaking: # This method overrides the default by forcing an :only option to be limited to entries in our # PUBLIC_FIELDS list def serializable_hash(options = nil) options ||= {} options:only ||= options:only += PUBLIC_FIELDS options:only. Uniq!

Super(options) end This basically allows you to have a list of fields that are allowed for your public API, and you cannot accidentally expose the whole object. You can still expose specific fields manually, but by default your object is secure for . To_json, .

To_xml, etc.

Actually, this should probably just default when :only isn't specified, otherwise it changes the intent of using :only. Oh, well, still my point is the same. – Nerdmaster Feb 9 at 1:10.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions