在我的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模板永远不会被调用
发布评论