更新:
这个问题没有得到适当的探讨。真正的问题在于render :json
。
在原始问题中粘贴第一个代码将产生预期的结果。然而,仍然有一个警告。请参阅此示例:
render :json => current_user
和不是一样吗?
render :json => current_user.to_json
也就是说,render :json
不会自动调用与User对象关联的to_json
方法。事实上,如果to_json
在User
模型上被覆盖,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
有什么想法吗?
https://stackoverflow.com/questions/2572284
复制相似问题