我对问题https://stackoverflow.com/a/62441675/385730发布了类似的答案。
您可以覆盖脚手架生成器lib/rails/generators/erb/scaffold/scaffold_generator.rb
文件。
第 1 步:
复制最新scaffold_generator.rb
文件。
mkdir -p lib/rails/generators/erb/scaffold && cp $(bundle show railties)/lib/rails/generators/erb/scaffold/scaffold_generator.rb lib/rails/generators/erb/scaffold/
第 2 步:
添加自定义代码以生成.js.erb
您想要的文件。
# frozen_string_literal: true
require "rails/generators/erb"
require "rails/generators/resource_helpers"
module Erb # :nodoc:
module Generators # :nodoc:
class ScaffoldGenerator < Base # :nodoc:
include Rails::Generators::ResourceHelpers
argument :attributes, type: :array, default: [], banner: "field:type field:type"
def create_root_folder
empty_directory File.join("app/views", controller_file_path)
end
def copy_view_files
available_views.each do |view|
formats.each do |format|
filename = filename_with_extensions(view, format)
template filename, File.join("app/views", controller_file_path, filename)
end
end
javascript_views.each do |view|
path = File.join('app', 'views', controller_file_path, "#{view}.js.erb")
File.open(path, "w")
end
end
private
def available_views
%w(index edit show new _form)
end
def javascript_views
%w(index show create update)
end
end
end
end
现在,当您运行脚手架生成器时,您将看到.js.erb
创建的新文件。