3

How can I trigger a scaffold generation from a view?

For example, let's say I have a method like this:

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

How can I make a button on my "example_page.html.erb" trigger this method to execute the command on the server? (No worries about security here)

2 Answers2

2

1: Create a form using Form Tag

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

2: Write a routes to match the incoming request.

 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
Gupta
  • 8,882
  • 4
  • 49
  • 59
1

If you are creating a button or link it should be pointed to a url path not just a helper method. A quick fix for this is add a path to the helper method.

So you can try

in helper

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

and in view

<%= button_to "Scaffold Generation", scaffold_generation(root_path), :method => :get %>
Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74