我正在尝试编辑rails scaffold生成器,我想在其中向控制器添加自定义操作并将它们添加到路由中。我可以通过在lib目录中添加以下代码来编辑模型生成器:
#/lib/template/active_record/model.rb
<% module_namespacing do -%>
class <%= class_name %> < <%= parent_class_name.classify %>
def self.import1(file)
spreadsheet = Roo::Spreadsheet.open(file.path)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
puts row.to_hash
product = find_by(id: row["id"]) || new
product.attributes = row.to_hash
product.save!
end
end
<% attributes.select(&:reference?).each do |attribute| -%>
belongs_to :<%= attribute.name %><%= ', polymorphic: true' if attribute.polymorphic? %><%= ', required: true' if attribute.required? %>
<% end -%>
<% attributes.select(&:token?).each do |attribute| -%>
has_secure_token<% if attribute.name != "token" %> :<%= attribute.name %><% end %>
<% end -%>
<% if attributes.any?(&:password_digest?) -%>
has_secure_password
<% end -%>
end
<% end -%>
当我生成rails g scaffold时,我的控制器名:string..我可以看到它正在调用资源路径。它给我的路线增加了一条线。
我想要一个解决方案,在这里我可以添加两个操作,比如每当我生成scaffold并将它们添加到路由时,在我的控制器中进行test和import。我可以通过添加以下内容来编辑模板:
#/lib/templates/scaffold/index.html.erb
我需要在lib文件夹中写入或复制什么,该文件夹可以生成具有以下两个操作的控制器:
def import
# Module1.import(params[:file])
ProductionProductivity7.import1(params[:file])
redirect_to tests_path, notice: "Products imported."
end
在我的路线中,我希望添加如下内容:
resources :production_productivity9s do
collection { post :import }
collection { get :dropdown }
collection { get :test }
end
代替资源:生产效率9。我想要一个编辑控制器和路由的解决方案。我在网上搜索,没有找到任何解决办法。