众所周知,如果我们有这样的模型:
class TMem < ActiveRecord::Base
def expense
return 'OK'
end
end
表t_mems
没有字段expense
但我们可以访问控制器中的字段:
TMem.find(1).expense
但如果一个动作返回一个json:
render json: TMem.find(1)
我无法从ajax请求中获取字段expense
。它显示响应json不包含该字段。
所以我想知道如何查询模型,以便我可以从ajax请求中获取此字段。
答案 0 :(得分:0)
您需要使用自定义方法覆盖模型中的to_json
更改您的模型
class TMem < ActiveRecord::Base
def expense
return 'OK'
end
def to_json(options={})
options[:methods] ||= [:expense]
super(options)
end
end
现在,如果你致电to_json
TMem.first.to_json #=> "{\"t_mem\":{\"id\":1,\"expense\":"OK\"}}"