in Railscasts, Uncategorized

Railscast 038 Multibutton Form

The GitHub Repo

The Heroku App

What I love about following the Railscasts and actually implementing the small features is that making these apps are quick, I’m exposed to something I wouldn’t have been otherwise, and they are straightforward. This episode was no different.


<%= submit_tag 'Preview', name: 'preview_button' %>

The Preview button is similar to the the submit button, but it differs in it function. The name for the button defaults to commit when using the submit_tag helper. This is good when you need to create a normal submit button to create or update a record, but in the case of a preview button, you do not want to save the record just yet. Instead of having the name='commit we override this default by specifying the name should be equal to preview_button. With the name now equalling preview_button the parameters hash has "preview_button" => "Preview".


def create
  respond_to do |format|
    if params[:preview_button] || !
      format.html { render action: 'new' }
      format.json { render json: @project.errors, status: :unprocessable_entity }
      format.html { redirect_to @project, notice: 'Project was successfully created.' }
      format.json { render action: 'show', status: :created, location: @project }

We can then use the params[:preview_button] within our conditional in the create action. If params[:preview_button] is not nil, then the controller will redirect to the new view while still having the preview_button parameter present in the URL. If there is no params[:preview_button] defined, then we know that the form was submitted through the normal submit button and not the preview button.


<% if params[:preview_button] %>
  <div id="preview">
    <h2><%= %></h2>
    <%= textilize @project.description %>
<% end %>

When we are redirected to the new view, the params[:preview_button] is still defined. We can use this in another conditional within our view to display a preview. Here we are previewing the project’s description using the textilize text helper. This was deprecated back in Rails 2, but I found a gem that dropped in to Rails 3+ that adds this back. There has to be a reason that the Rails Core Team deprecated this, so I do not plan to use this again. Instead I might reuse the code I used to render markdown to the view from my Markdown Todo List Rails API App