问题
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
回答1:
Comment out gem jbuilder
in your Gemfile
and respond_to
blocks won't be generated.
回答2:
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 ).
回答3:
You'll notice that the JSON response is coded directly into the template for the rails generator here:
https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
I think something to note is that the scaffold generator is really intended to illustrate and moreover educate on how the Rails stack works, it shows how you can edit the controller to provide many different formats to suit your needs!
回答4:
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.
来源:https://stackoverflow.com/questions/14027644/skip-json-format-in-rails-generate-scaffold