调用渲染和保留隐式渲染运行之间的区别是什么?

时间:2015-01-15 16:34:17

标签: ruby-on-rails json renderer

我正在开发我的api,我想把所有东西都呈现为Json。

在控制器中我有:

 def index
    @items = Item.all
 end

呈现以下内容:

<html><head><style type="text/css"></style></head><body></body></html>

这很奇怪,因为我没有任何布局文件,而且请求是针对json mime的。

但如果我只是在没有参数的情况下添加对render的调用,则会突然使用jbuilder模板。

 def index
    @items = Item.all
    render 
 end

我真的不明白为什么隐式渲染器只在HTML中渲染,而我必须调用render而不使用参数来获取json响应。

任何人都可以向我解释这个吗?

1 个答案:

答案 0 :(得分:0)

我不能确定这里提供的是什么,但有一种理解的格式被传递。

让我们说你的代码看起来像这样(我需要控制器):

class ItemsController < ApplicationController
  def index
    @items = Item.all
  end
end

,你的路线看起来像这样

resources :items

这真的是这样说的:

resources :items, defaults: {format: 'html'}

因此,如果没有其他方法,它将假设您正在寻找HTML响应。

试试这个:     class ItemsController&lt; ApplicationController的       respond_to:json       def指数         @items = Item.all       结束     端

然后在您的视图中,创建index.json.erb或:

class ItemsController < ApplicationController
  respond_to :json
  def index
    render json: Item.all.to_json
  end
end
相关问题