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

时间:2016-01-04 12:57:47

标签: ruby-on-rails ruby ruby-on-rails-4 rails-generators

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

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

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

如何在我的“example_page.html.erb”上创建一个按钮,触发此方法在服务器上执行命令? (这里不担心安全问题)

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

如果要创建按钮或链接,则应指向url路径,而不仅仅是帮助方法。快速解决此问题的方法是添加辅助方法的路径。

所以你可以试试

in helper

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

并在视野中

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