2015-01-15 101 views
3

我正在開發我的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沒有PARAMS獲得JSON響應。

任何人都可以解釋這一點嗎?

回答

0

我不能確定這裏提供了什麼,但有一個理解的格式被傳遞。

因此,可以說你的代碼看起來像這樣(我需要的控制器):

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

和你的路線是這樣的

resources :items 

這究竟說的是這樣的:

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

因此,如果沒有其他的事情做,它會假設你正在尋找一個HTML響應。

試試這個: 類上述ItemsController <的ApplicationController respond_to代碼:JSON 高清指數 @items = Item.all 結束 結束

然後在您的視圖,創建index.json.erb或:

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