【发布时间】:2018-12-15 17:05:33
【问题描述】:
我正在尝试编辑 Rails 脚手架生成器,我想在其中向我的控制器添加自定义操作并将它们添加到路由中。我可以通过在我的 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 my_controller name:string .. 我可以看到它正在调用 resource_route。它在我的路线中添加了一条线。
我想要一个解决方案,每当我生成脚手架并将它们添加到路由中时,我都可以在控制器中添加两个操作,例如测试和导入。我可以通过添加以下内容来编辑我的模板:
#/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
而不是资源:production_productivity9s。我想要一个编辑控制器和路由的解决方案。我在网上搜索,我没有看到任何解决方案。
【问题讨论】:
标签: ruby-on-rails edit scaffold