JBuilder template never gets called

坚强是说给别人听的谎言 提交于 2020-01-01 17:56:33

问题


In my Rails 4 app, I have a API::V1::ClustersController structured like so:

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

  def index
    @clusters = Cluster.all

    render json: @clusters
  end
class

In my app/views/api/v1/clusters/index.json.jbuilder view:

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

In my routes:

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

Unfortunately, the following is the json output when I hit 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"
    }
  ]
}

I don't know what else to do. Any help is appreciated.


回答1:


In this case you need to use respond_with instead of render in you controller

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

  def index
    @clusters = Cluster.all

    respond_with @clusters
  end
end

When you call render json: @clusters its like you call render @clusters.to_json so your controller doesn't render a template. if you want to use render you can include this in a respond_to block, but respond_with is more elegant.



来源:https://stackoverflow.com/questions/24795090/jbuilder-template-never-gets-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!