除了html.erb文件之外,是否有(简单)方法配置默认生成器以为每个操作生成js.erb文件?
答案 0 :(得分:0)
您可以覆盖支架生成器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
文件。
答案 1 :(得分:0)
@dale-zak 的回答创建了一个空的 js 文件,没有来自我的 lib/templates/erb/scaffold/index.js.erb.tt
的内容
带有这个循环的代码对我有用:
javascript_views.each do |view|
filename = filename_with_extensions(view, :js)
template filename, File.join("app/views", controller_file_path, filename)
end