gpt4 book ai didi

ruby-on-rails - 覆盖 as_json 没有效果?

转载 作者:行者123 更新时间:2023-12-01 04:18:06 26 4
gpt4 key购买 nike

我试图在我的一个模型中覆盖 as_json,部分是为了包含来自另一个模型的数据,部分是为了去除一些不必要的字段。从我读到的,这是 Rails 3 中的首选方法。为了简单起见,假设我有类似的东西:

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

在我的 Controller 中
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 输出。我只是语法错误吗?

最佳答案

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

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

关于ruby-on-rails - 覆盖 as_json 没有效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2924884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com