首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Rails中重写to_json?

如何在Rails中重写to_json?
EN

Stack Overflow用户
提问于 2010-04-04 02:49:10
回答 4查看 50.3K关注 0票数 95

更新:

这个问题没有得到适当的探讨。真正的问题在于render :json

在原始问题中粘贴第一个代码将产生预期的结果。然而,仍然有一个警告。请参阅此示例:

render :json => current_user

不是一样吗?

render :json => current_user.to_json

也就是说,render :json不会自动调用与User对象关联的to_json方法。事实上,如果to_jsonUser模型上被覆盖,render :json => @user将生成下面描述的ArgumentError

摘要

# works if User#to_json is not overridden
render :json => current_user

# If User#to_json is overridden, User requires explicit call
render :json => current_user.to_json

在我看来,这一切都很愚蠢。这似乎是在告诉我,当指定了类型Model#to_json时,render实际上并没有调用:json。有人能解释一下到底是怎么回事吗?

任何可以在这方面帮助我的genii都可能回答我的另一个问题:How to build a JSON response by combining @foo.to_json(options) and @bars.to_json(options) in Rails

原问题:

我在SO上看过一些其他的例子,但我没有做我想做的事情。

我在试着:

class User < ActiveRecord::Base

  # this actually works! (see update summary above)
  def to_json
    super(:only => :username, :methods => [:foo, :bar])
  end

end

我要把ArgumentError: wrong number of arguments (1 for 0)弄进来

/usr/lib/ruby/gems/1.9.1/gems/activesupport-2.3.5/lib/active_support/json/encoders/object.rb:4:in `to_json

有什么想法吗?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2572284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档