(Rails 4.2) 如何从View触发生成脚手架?

(Rails 4.2) How to trigger scaffold generation from View?

如何从视图中触发脚手架生成?

例如,假设我有这样的方法:

def scaffold_generation
  system "rails g scaffold TodoList task author"
end

如何让我的 "example_page.html.erb" 上的按钮触发此方法以在服务器上执行命令? (这里不用担心安全问题)

1: 使用 Form Tag

创建表单
<%= form_tag('/create_scaffold') do -%>
  <div><%= submit_tag 'Create Scaffold' %></div>
<% end %>

2:写一个路由来匹配传入的请求。

 match '/create_scaffold', to: 'examples#scaffold_generation', via: :all

3:

class ExamplesController < ApplicationController

   def scaffold_generation
      system "rails g scaffold TodoList task author"
      system "rake db:migrate" #=> use this so that, it won't throw any errors.
      render :text => "Whoa !!! Done"
   end
end

如果您正在创建一个按钮或 link,它应该指向一个 url 路径,而不仅仅是一个辅助方法。一个快速解决方法是添加辅助方法的路径。

所以你可以试试

在助手中

def scaffold_generation(url)
  system "rails g scaffold TodoList task author"
  url
end

在视图中

<%= button_to "Scaffold Generation", scaffold_generation(root_path), :method => :get %>