Rails控制器在浏览器中呈现JSON

nic*_*tme 8 json ruby-on-rails

我有一个简单的控制器,我已经响应了两个htmljson.我正在使用jsonBackbone应用程序的响应.一切都按预期工作,除了当我单击使用该show方法的链接,然后单击后退按钮时,该index方法只是JSON在浏览器中打印一大串.如果我刷新,它会按预期显示HTML.这是控制器.

class RecipesController < ApplicationController
  def index
    @user = User.find(params[:user_id])
    @recipes = Recipe.all

    respond_to do |format|
      format.html
      format.json { render json: Recipe.where(user_id: params[:user_id]).featured }
    end
  end
  ...
end
Run Code Online (Sandbox Code Playgroud)

我尝试添加一个检查response.xhr?,并且仅在呈现JSONAJAX请求时才进行渲染,但这不起作用.

编辑

这是一个不使用turbolinks的Rails 3应用程序.

编辑2

这是相关的Backbone代码.

# app/assets/javascripts/collections/recipe_list_.js.cofee
@App.Collections.RecipeList = Backbone.Collection.extend
  url: ->
    "/users/#{@userId}/recipes"
  model: window.App.Models.Recipe
  initialize: (opts) ->
    @userId = opts.userId


# app/assets/javascripts/app.js.coffee
$ ->
  urlAry = window.location.href.split('/')
  userId = urlAry[urlAry.length - 2]
  App = window.App
  App.recipeList = new App.Collections.RecipeList(userId: userId)
  App.recipeListView = new App.Views.RecipeListView
Run Code Online (Sandbox Code Playgroud)

som*_*ude 3

你可以尝试使用 /recipes.html 和 /recipes.json 和 /recipes/1.html 和 /recipes/1.json

而不是依赖主干和历史记录来始终发送正确的标头