在Rails中使用:include默认为to_json [英] defaults for to_json in Rails with :include

查看:49
本文介绍了在Rails中使用:include默认为to_json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个属于用户的模型帖子.要转换为json,我要做类似的事情

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 => [:email, :id]}, 
               :only => [:title, :id])

但是,我想为此设置一些默认值,因此不必每次都指定:only.我正在尝试覆盖as_json以完成此操作.当我在User模型中添加as_json时,当我执行@ user.to_json时会调用它,但是当用户包含在@ reply.to_json中时,我为User覆盖的as_json将被忽略.

However, I want to set some defaults for this so I don't have to specify :only everytime. I am trying to override as_json to accomplish this. When I add as_json in User model, it is called when I do @user.to_json but when user is included in @reply.to_json, my overriden as_json for User is ignored.

我如何进行这项工作?

How do I make this work?

谢谢

推荐答案

您可以通过覆盖模型中的serializable_hash来做到这一点,就像这样:

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

这将影响所有可序列化的方法,包括serializable_hashto_jsonto_xml.

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

这篇关于在Rails中使用:include默认为to_json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆