覆盖as_json无效吗? [英] Overriding as_json has no effect?
问题描述
我试图在我的一个模型中覆盖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屋!