在rails中跳过JSON格式生成脚手架

当你使用像rails g scaffold Thing这样的命令生成一个rails脚手架时,有什么方法可以避免让人烦恼

 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 

只需克隆文件

https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb

到你的

 lib/rails/generators/rails/scaffold_controller/templates/controller.rb 

应用程序中的路径并自定义您想要的内容。 此外,您可以编写自己的脚手架生成器( http://guides.rubyonrails.org/generators.html )。

在你的Gemfile注释掉gem jbuilder并且不会生成respond_to块。

您会注意到JSON响应直接编码到rails生成器的模板中:

https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb

我想要注意的是脚手架生成器实际上是为了说明,而且教育Rails堆栈如何工作,它显示了如何编辑控制器以提供许多不同的格式以满足您的需求!

我想你错过了一个机会。 首先,您将教授非标准的Rails,因此当您的学生在自己的安装中看到正常版本时可能会感到困惑。

更重要的是,控制器的格式是有原因的。 Rails强调REST,它鼓励通过多种数据格式访问资源。 许多现代应用程序不再强调较慢的服务器呈现的html / erb响应,而是支持json API。 我知道这是你的OP后一年多一点,你在课堂上的时间有限,只是为可能发生的任何人添加一些想法。 我想你可以挥动你的回应,并告诉他们它正在为你未来的可能性做好准备。