覆盖as_json无效吗? [英] Overriding as_json has no effect?

查看:133
本文介绍了覆盖as_json无效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的一个模型中覆盖as_json,部分地包括来自另一个模型的数据,部分地去除一些不必要的字段.从我阅读的内容来看,这是Rails 3中的首选方法.为简单起见,假设我有类似以下内容:

I'm trying to override as_json in one of my models, partly to include data from another model, partly to strip out some unnecessary fields. From what I've read this is the preferred approach in Rails 3. To keep it simple, let's say I've got something like:

class Country < ActiveRecord::Base
  def as_json(options={})
    super(
      :only => [:id,:name]
    )
  end
end

以及在我的控制器中

def show
  respond_to do |format|
    format.json  { render :json => @country }
  end
end

无论我如何尝试,输出始终包含完整数据,该字段未通过:only"子句过滤.基本上,我的替代似乎并没有生效,但是如果我将其更改为,说...

Yet whatever i try, the output always contains the full data, the fields are not filtered by the ":only" clause. Basically, my override doesn't seem to kick in, though if I change it to, say...

class Country < ActiveRecord::Base
  def as_json(options={})
    {foo: "bar"}
  end
end

...我确实得到了预期的JSON输出.我是否只是语法错误?

...I do indeed get the expected JSON output. Have I simply got the syntax wrong?

推荐答案

这是一个错误,但可惜没有奖赏:

It is a bug, but alas no prize:

https://rails.lighthouseapp.com/projects/8994/tickets/3087

这篇关于覆盖as_json无效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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