如何从Ruby on Rails输出JSON? [英] How do you output JSON from Ruby on Rails?

查看:84
本文介绍了如何从Ruby on Rails输出JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个可以通过AJAX创建/更新的模型.您如何在Ruby on Rails中做到这一点?

I'm looking to have a model that gets created / updated via AJAX. How do you do this in Ruby on Rails?

而且,更具体地说:如何在RoR中输出JSON?

Also, more specifically: how do you output JSON in RoR?

def create
  response = {:success => false}
  @source = Source.new(params[:source])
  if @source.save
    response.success = true
  end
  render :json => response.to_json
end

推荐答案

所有您需要做的就是使用对象调用render:json,就像这样:

All you need to do is call render :json with an object, like so:

render :json => my_object

对于大多数对象,这将起作用.如果它是一个ActiveRecord对象,请确保查看as_json以了解其工作原理.对于上面说明的情况,您的哈希将转换为json并返回.

For most objects, this will just work. If it's an ActiveRecord object, make sure to look at as_json to see how that works. For your case illustrated above, your hash will be transformed to json and returned.

但是,您确实有一个错误:您无法通过response.success访问成功密钥-您应该执行response [:success]

However, you do have an error: you cant access the success key via response.success -- you should instead do response[:success]

这篇关于如何从Ruby on Rails输出JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆