在 Rails 中,如何使用视图呈现 JSON?

问题描述:

假设你在你的用户控制器中并且你想得到一个显示请求的 json 响应,如果你能在你的视图/用户/目录中创建一个文件,命名为 show.json 并在你的users#show 操作完成,它呈现文件.

Suppose you're in your users controller and you want to get a json response for a show request, it'd be nice if you could create a file in your views/users/ dir, named show.json and after your users#show action is completed, it renders the file.

目前你需要做一些事情:

Currently you need to do something along the lines of:

def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json{
      render :json => @user.to_json
    }
  end
end

但如果你能创建一个像这样自动渲染的 show.json 文件就好了:

But it would be nice if you could just create a show.json file which automatically gets rendered like so:

def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json
  end
end

这会为我省去很多痛苦,并且会洗去我在控制器中渲染 json 时那种可怕的肮脏感觉

This would save me tons of grief, and would wash away that horribly dirty feeling I get when I render my json in the controller

你应该能够在你的 respond_to 块中做这样的事情:

You should be able to do something like this in your respond_to block:

respond_to do |format|
    format.json 
    render :partial => "users/show.json"
end

这将在 app/views/users/_show.json.erb 中呈现模板.

which will render the template in app/views/users/_show.json.erb.