Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip JSON format in rails generate scaffold

When you generate a rails scaffold using a command like rails g scaffold Thing is there any way to avoid getting that annoying

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

stuff in your controller?

I'm trying to teach a class on Rails and I'd like to start by having them generate a scaffold, but with all the json formatting it's much more complicated than it needs to be. I'd be much happier if they could generate a scaffold that created a controller like this:

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
like image 445
mattangriffel Avatar asked Dec 25 '12 04:12

mattangriffel


3 Answers

Comment out gem jbuilder in your Gemfile and respond_to blocks won't be generated.

like image 97
e-fisher Avatar answered Oct 05 '22 02:10

e-fisher


Just clone the file

https://github.com/rails/rails/blob/v5.2.2/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb

to your

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

path in your application and customize what you want. Also, you can write your own generators for scaffolding ( http://guides.rubyonrails.org/generators.html ).

like image 27
VadimAlekseev Avatar answered Oct 05 '22 03:10

VadimAlekseev


I think you'd be missing an opportunity. For one thing, you'd be teaching non-standard Rails, so your students might be confused when they see the normal version in their own installations.

More importantly, the controllers are formatted that way for a reason. Rails puts an emphasis on REST, which encourages access to resources via multiple data formats. Many modern apps are de-emphasizing slower server-rendered html/erb responses in favor of json APIs. I realize this is a little over a year after your OP, and you have limited time in class, just adding some thoughts for anyone who might happen by. I think you could wave your hand over the respond_to and tell them it's setting you up for some future possibilities.

like image 22
Stephen C Avatar answered Oct 05 '22 01:10

Stephen C