Multi Button Form in Rails 5

Steps

Step 1

Add description field to projects table.

$ rails g migration add_description_to_projects description:text

Migrate the database.

rails db:migrate

Step 2

Add the text area for the project description in the form partial.

<div class="field">
  <%= f.label :description %>
  <%= f.text_area :description %>
</div>

Step 3

The new project page has preview button.

<div class="actions">
  <%= f.submit button_name %>
  <%= f.submit 'Preview', name:  'preview_button'  %>
</div>

We pass the value for button_name in the new.html.erb:

<%= render 'form', project: @project, button_name: 'Create'  %>

Step 4

You can see the commit key has 'Preview' when you click on Preview button.

Started POST "/projects" for ::1 at 2016-03-25 19:55:12 -0700
Processing by ProjectsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"AwUw", "project"=>{"name"=>"", "description"=>""}, "commit"=>"Preview"}
Unpermitted parameter: description
   (0.1ms)  begin transaction
  SQL (0.4ms)  INSERT INTO "projects" ("name", "created_at", "updated_at") VALUES (?, ?, ?)  [["name", ""], ["created_at", 2016-03-25 19:55:12 UTC], ["updated_at", 2016-03-25 19:55:12 UTC]]
   (0.6ms)  commit transaction
Redirected to http://localhost:3000/projects/5
Completed 302 Found in 27ms (ActiveRecord: 1.1ms)

Let's change the name of the Preview button to preview_button. This will allow us to distinguish the Preview button from Create button in our controller.

Step 5

We can add the preview to the create a new project page.

<%= form_for(project) do |f| %>

    <% if params[:preview_button] %>
      <%= project.description %>
    <% end %>

  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %>
    <%= f.text_area :description %>
  </div>
  <div class="actions">
    <%= f.submit button_name %>
    <%= f.submit 'Preview', name:  'preview_button'  %>
  </div>
<% end %>

Step 6

We can handle the preview feature in the projects controller create action.

def create
  @project = Project.new(params[:project])
  if params[:preview_button] || !@project.save
    render :action => 'new'
  else
    flash[:notice] = "Successfully created project."
    redirect_to project_path(@project)
  end
end

Step 7

We must now allow the project description field.

def project_params
  params.require(:project).permit(:name, :description)
end

Step 8

Fill out the new project form and click Preview to see the preview. Note: The last version of rails that had textilize was 2.3.8. It is not available in Rails 5 anymore.

Summary

In this article, you learned how to use multiple buttons in a Rails 5 app.


Related Articles