【问题标题】:what's the difference between calling render and leaving the implicit render run?调用渲染和让隐式渲染运行有什么区别?
【发布时间】:2015-03-14 03:13:24
【问题描述】:

我正在开发我的 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 响应。

谁能给我解释一下?

【问题讨论】:

    标签: ruby-on-rails json renderer


    【解决方案1】:

    我无法确定此处提供的内容,但传递了一种可以理解的格式。

    假设您的代码如下所示(我需要控制器):

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

    你的路线看起来像这样

    resources :items
    

    这句话的真正含义是:

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

    所以如果什么都不做,它会假设你正在寻找一个 html 响应。

    试试这个: 类 ItemsController

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

    class ItemsController < ApplicationController
      respond_to :json
      def index
        render json: Item.all.to_json
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 2013-03-25
      • 2020-01-31
      • 2015-02-17
      • 2021-06-19
      相关资源
      最近更新 更多