JBuilder 模板永远不会被调用

Kur*_*ler 3 ruby-on-rails jbuilder

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

class Api::V1::ClustersController < ApplicationController
  respond_to :json

  def index
    @clusters = Cluster.all

    render json: @clusters
  end
class
Run Code Online (Sandbox Code Playgroud)

在我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
Run Code Online (Sandbox Code Playgroud)

在我的路线中:

namespace :api, defaults: { format: :json } do
  namespace :v1 do
    authenticated :user do
      resources :clusters
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

不幸的是,以下是我点击时的 json 输出http://localhost:3000/api/v1/clusters.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"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

Yan*_*ERY 5

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

class Api::V1::ClustersController < ApplicationController
  respond_to :json

  def index
    @clusters = Cluster.all

    respond_with @clusters
  end
end
Run Code Online (Sandbox Code Playgroud)

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

  • 您也不必调用 `render` 或 `respond_with`。不过还是谢谢你的帮助! (3认同)