简体   繁体   English

如何从Ruby on Rails输出JSON?

[英]How do you output JSON from Ruby on Rails?

I'm looking to have a model that gets created / updated via AJAX. 我希望有一个通过AJAX创建/更新的模型。 How do you do this in Ruby on Rails? 你是如何在Ruby on Rails中做到这一点的?

Also, more specifically: how do you output JSON in RoR? 另外,更具体地说:如何在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

All you need to do is call render :json with an object, like so: 您需要做的就是使用对象调用render:json,如下所示:

render :json => my_object

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. 如果它是一个ActiveRecord对象,请务必查看as_json以了解其工作原理。 For your case illustrated above, your hash will be transformed to json and returned. 对于上面说明的情况,您的哈希将转换为json并返回。

However, you do have an error: you cant access the success key via response.success -- you should instead do response[:success] 但是,您确实有错误:您无法通过response.success访问成功密钥 - 您应该执行响应[:success]

jimothy's solution is really good butI believe it isn't scalable in the long term. jimothy的解决方案非常好,但我认为从长远来看它不具备可扩展性。 Rails is meant to be a model, view, and controller framework. Rails旨在成为模型,视图和控制器框架。 Right now JSON is cheated out of a view in default rails. 现在,JSON被默认导轨中的视图所欺骗。 However there's a great project called RABL which allows JSON view. 然而,有一个名为RABL的伟大项目允许JSON视图。 I've written up some arguments for why I think it's a good option and how to get up and running with it quickly. 我已经写了一些论据,为什么我认为这是一个很好的选择,以及如何快速启动和运行它。 See if this is useful for you: http://blog.dcxn.com/2011/06/22/rails-json-templates-through-rabl/ 看看这对你有用: http//blog.dcxn.com/2011/06/22/rails-json-templates-through-rabl/

@source = Source.new(params[:source])

respond_to do | f |
  f.html {
    # do stuff to populate your html view
    # maybe nothing at all because @source is set
  }

  f.any(:xml, :json) { 
    render request.format.to_sym => @source 
  }
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM