JBuilder模板永远不会被调用

在我的Rails 4应用程序中,我有一个API::V1::ClustersController结构如下:

 class Api::V1::ClustersController < ApplicationController respond_to :json def index @clusters = Cluster.all render json: @clusters end class 

在我的app/views/api/v1/clusters/index.json.jbuilder视图中:

 json.array!(@clusters) do |cluster| json.extract! cluster, :id, :index json.url cluster_url(cluster, format: :json) end 

在我的路线:

 namespace :api, defaults: { format: :json } do namespace :v1 do authenticated :user do resources :clusters end end end 

不幸的是,当我点击http://localhost:3000/api/v1/clusters.json时,以下是json输出:

 { clusters: [ { id: 1, organization: null, number: null, name: "Roob Group", created_at: "2014-07-16T17:41:09.214Z", updated_at: "2014-07-16T17:41:09.214Z" }, { id: 2, organization: null, number: null, name: "Lesch LLC", created_at: "2014-07-16T17:41:09.302Z", updated_at: "2014-07-16T17:41:09.302Z" } ] } 

我不知道还能做什么。 任何帮助表示赞赏。

在这种情况下,您需要在控制器中使用respond_with而不是render

 class Api::V1::ClustersController < ApplicationController respond_to :json def index @clusters = Cluster.all respond_with @clusters end end 

当您调用render json: @clusters就像调用render @clusters.to_json因此控制器不会呈现模板。 如果你想使用render你可以将它包含在respond_to块中,但respond_with更优雅。