在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中呈现模板.