问题
When I use the Rails scaffold generator to create my Rails-files, it creates among others a controller file. e.g.
rails generate scaffold potato
generates:
app/controllers/potatos_controller.rb
For my project I want this file a little more specific. E.g. I want to change this automatic generated action:
def create
@potato = Potato.new(potato_params)
respond_to do |format|
if @potato.save
format.html { redirect_to @potato, notice: 'Potato was successfully created.' }
format.json { render :show, status: :created, location: @potato }
else
format.html { render :new }
format.json { render json: @potato.errors, status: :unprocessable_entity }
end
end
end
to use a I18n-translation instead of the hardcoded 'Potato was successfully created.' Also I want to change some indentations, since rubocop is always complaining about it.
I have found the template of the scaffold-generator and now want to make my changes. For this I have created a file in my project:
lib/templates/rails/scaffold_controller/templates/controller.rb
In this file I have made my changes. (e.g. I changed the line
redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully created.'" %>
to
redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} THIS IS A TEST.'" %>
But unfortunately the changes don't work. The scaffold generator still uses its own template. So what am I doing wrong here? Am I missing a step?
Update: Here is the output of the generate-command:
rails generate scaffold potato
Running via Spring preloader in process 31479
invoke active_record
...
invoke scaffold_controller
create app/controllers/potatos_controller.rb
...
Screenshot of the railties:
回答1:
Rails 4 shows you which template is using
rails generate scaffold potato
...
invoke scaffold_controller
You should host your modified templates in your project, i.e.lib/templates/rails/scaffold_controller/controller.rb
.
Please note that the Responders gem might change the generator used tolib/templates/rails/responders_controller/controller.rb
.
回答2:
If anyone finds it useful, you can copy the default railties controller scaffold templates to your own project by running this command in your project directory:
mkdir -p lib/templates/rails/scaffold_controller && \
cp $(bundle show railties)/lib/rails/generators/rails/scaffold_controller/templates/* \
lib/templates/rails/scaffold_controller
If you use Rails 5.2 and jbuilder, you should use the jbuilder
scaffolders as a base instead:
mkdir -p lib/templates/rails/scaffold_controller && \
cp $(bundle show jbuilder)/lib/generators/rails/templates/* \
lib/templates/rails/scaffold_controller
来源:https://stackoverflow.com/questions/35337732/changing-scaffold-controller-generator-templates-in-rails