问题描述
在我的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
不幸的是,当我按下http://localhost:3000/api/v1/clusters.json
时,以下是json输出:
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.
推荐答案
在这种情况下,您需要在控制器中使用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模板永远不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!