如何在Rails 3中将哈希渲染为JSON

Cor*_*rdi 4 api json ruby-on-rails ruby-on-rails-3

我找到了如何在Rails 3中渲染ActiveRecord对象,但是我无法弄清楚如何渲染任何自定义对象.我正在写一个没有ActiveRecord的应用程序.我尝试过这样的事情:

class AppController < ApplicationController
  respond_to :json

  ...
  def start
    app.start
    format.json { render :json => {'ok'=>true} }
  end
end
Run Code Online (Sandbox Code Playgroud)

Jos*_*sey 7

当您指定a时respond_to,在您的操作中,您将进行匹配respond_with:

class AppControlls < ApplicationController
  respond_to :json

  def index
    hash = { :ok => true }
    respond_with(hash)
  end
end
Run Code Online (Sandbox Code Playgroud)

它看起来像你的混为一谈旧respond_to do |format|与新的样式块respond_to,respond_with语法.这篇edgerails.info帖子很好地解释了它.