【发布时间】:2010-05-27 21:01:12
【问题描述】:
我试图在我的一个模型中覆盖 as_json,部分是为了包含来自另一个模型的数据,部分是为了去除一些不必要的字段。根据我的阅读,这是 Rails 3 中的首选方法。为了简单起见,假设我有类似的东西:
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”子句过滤。基本上,我的覆盖似乎没有启动,但如果我将其更改为...
class Country < ActiveRecord::Base
def as_json(options={})
{foo: "bar"}
end
end
...我确实得到了预期的 JSON 输出。我只是弄错了语法吗?
【问题讨论】:
标签: ruby-on-rails json model overriding