这个问题没有得到适当的探索.真正的问题在于render :json.
原始问题中的第一个代码粘贴将产生预期结果.但是,仍然有一个警告.看这个例子:
render :json => current_user
是不一样的
render :json => current_user.to_json
也就是说,render :json不会自动调用to_json与User对象关联的方法.实际上,如果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
Run Code Online (Sandbox Code Playgroud)
这一切对我来说都很愚蠢.这似乎告诉我,在指定类型时render实际上并没有调用.谁能解释一下这里到底发生了什么?Model#to_json:json
任何可以帮助我的genii都可以回答我的另一个问题:如何通过在Rails中组合@ foo.to_json(options)和@ bars.to_json(options)来构建JSON响应
我在SO上看过其他一些例子,但我没有做我正在寻找的事情.
我尝试着:
class User < ActiveRecord::Base
# this actually …Run Code Online (Sandbox Code Playgroud)