ruby-on-railsrubyruby-on-rails-4rails-generators

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


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)


Solution

  • 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