【问题标题】:JBuilder template never gets calledJBuilder 模板永远不会被调用
【发布时间】:2014-09-07 19:49:27
【问题描述】:

在我的 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"
    }
  ]
}

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

【问题讨论】:

    标签: ruby-on-rails jbuilder


    【解决方案1】:

    在这种情况下,您需要在控制器中使用 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 更优雅。

    【讨论】:

    • 您也不必致电renderrespond_with。不过感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2012-10-27
    • 2013-10-12
    • 2012-03-27
    • 2013-08-29
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    相关资源
    最近更新 更多