defaults for to_json in Rails with :include

后端 未结 5 1034
悲&欢浪女
悲&欢浪女 2020-12-29 23:24

Let us say I have a model Post which belongs to a User. To convert to json, I do something like this

@reply.to_json(:include => {:user => {:only =>         


        
5条回答
  •  醉话见心
    2020-12-30 00:18

    You can do this by overriding serializable_hash in your model, like so:

    class Reply < ActiveRecord::Base
      def serializable_hash(options={})
        options = { 
          :include => {:user => {:only => [:email, :id]}, 
          :only => [:title, :id]
        }.update(options)
        super(options)
      end
    end
    

    This will affect all serializable methods, including serializable_hash, to_json, and to_xml.

提交回复
热议问题