How to customize to_json response in Rails 3

前端 未结 3 1696
孤独总比滥情好
孤独总比滥情好 2020-12-31 05:00

I am using respond_with and everything is hooked up right to get data correctly. I want to customize the returned json, xml and

3条回答
  •  难免孤独
    2020-12-31 05:41

    You can override as_json in your model. Something like:

    class Post < ActiveRecord::Base
      def as_json(options = {})
        {
          attribute: self.attribute, # and so on for all you want to include
          images:    self.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)

提交回复
热议问题