How to customize to_json response in Rails 3

前端 未结 3 1708
孤独总比滥情好
孤独总比滥情好 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:31

    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.

提交回复
热议问题