2012-12-25 44 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'视图的生成。这应该是被接受的答案。 –