JBuilder模板永远不会被调用

编程入门 行业动态 更新时间:2024-10-28 10:22:15
本文介绍了JBuilder模板永远不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

在我的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

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

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

推荐答案

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

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

调用render json: @clusters时就像调用render @clusters.to_json一样,因此控制器不会呈现模板.如果要使用render,则可以将其包含在respond_to块中,但是response_with更为优雅.

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.

更多推荐

JBuilder模板永远不会被调用

本文发布于:2023-11-08 09:42:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569031.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:永远不会   模板   JBuilder

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!