Geo*_*off 3 json ruby-on-rails
我希望有一个通过AJAX创建/更新的模型.你是如何在Ruby on Rails中做到这一点的?
另外,更具体地说:如何在RoR中输出JSON?
def create
response = {:success => false}
@source = Source.new(params[:source])
if @source.save
response.success = true
end
render :json => response.to_json
end
Run Code Online (Sandbox Code Playgroud)
您需要做的就是使用对象调用render:json,如下所示:
render :json => my_object
Run Code Online (Sandbox Code Playgroud)
对于大多数对象,这只会起作用.如果它是一个ActiveRecord对象,请务必查看as_json以了解其工作原理.对于上面说明的情况,您的哈希将转换为json并返回.
但是,您确实有错误:您无法通过response.success访问成功密钥 - 您应该执行响应[:success]