2012-12-25 57 views
14

當你使用如下命令rails g scaffold Thing產生導軌支架是有什麼辦法避免讓那個討厭的跳過JSON格式生成腳手架

respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @things } 
end 

的東西,在你的控制?

我想教一個關於Rails的類,我想先讓他們生成一個腳手架,但所有的json格式都比它需要的複雜得多。我會覺得很開心,如果他們能產生創造了這樣一個控制器支架:

class ThingsController < ApplicationController 

    def index 
    @things = Thing.all 
    end 

    def show 
    @thing = Thing.find(params[:id]) 
    end 

    def new 
    @thing = Thing.new 
    end 

    def edit 
    @thing = Thing.find(params[:id]) 
    end 

    def create 
    @thing = Thing.new(params[:thing]) 
     if @thing.save 
     redirect_to @thing, notice: 'Thing was successfully created.' 
     else 
     render: "new" 
     end 
    end 
    end 

    def update 
    @thing = Thing.find(params[:id]) 
     if @thing.update_attributes(params[:thing]) 
     redirect_to @thing, notice: 'Thing was successfully updated.' 
     else 
     render: "edit" 
     end 
    end 
    end 

    def destroy 
    @thing = Thing.find(params[:id]) 
    @thing.destroy 
    redirect_to things_url 
    end 
end 

回答

0

我想你會錯過一個機會。首先,你會教非標準的Rails,所以當你的學生在他們自己的安裝中看到正常版本時可能會感到困惑。

更重要的是,控制器被格式化的原因。 Rails強調REST,它鼓勵通過多種數據格式訪問資源。許多現代應用程序不再強調服務器渲染的html/erb響應,而是支持json API。我意識到這是在你的OP之後一年多一點,你在課堂上的時間有限,只是爲任何可能發生的事情添加一些想法。我認爲你可以在respond_to上揮動手,並告訴他們這會讓你有一些未來的可能性。

27

在您的Gemfilerespond_to中不會生成註釋掉gem jbuilder塊。

+0

在** rails 5 **中仍然有效,並且也省略了'.jbuilder'視圖的生成。這應該是被接受的答案。 –