How to Preview Form Data Before Save in Rails

The main aim of writing this blog is to get a better solution for implementing this. But for now let’s work with what I have.

First thing’s first, create a new Rails app:

 rails new form_preview

Next, we generate a scaffold for Student. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.

 rails g scaffold Student name admission_number age:integer admission_date:date 
rails db:create 
rails db:migrate

Using a Preview Button

Lets start by modifying the _form.html.erb

<% if params[:preview_button] %>
<h5>Are these the attributes you want to save?</h5>
<p>Name: <%= student.name%> </p>
<p>Admission Number: <%= student.admission_number%> </p>
<p>Age: <%= student.age%> </p>
<p>Date: <%= student.admission_date%> </p>
<% end %>
.......
<%= submit_tag 'Preview', :name => 'preview_button' %>

And our students_controller.rb

def create
@student = Student.new(student_params)
respond_to do |format|
if params[:preview_button] || !@student.save
format.html { render :new }
format.json { render json: @student.errors, status: :unprocessable_entity }
else
format.html { redirect_to @student, notice: 'Student was successfully created.' }
format.json { render :show, status: :created, location: @student }
end
end
end

Now when we click the preview button, we will have data displayed as follows:

Using a modal

In the partial _form.html.erb, I pass a unique id to each attribute, then get their values using the unique id as follows:

<div class="field">
<%= form.label :name %>
<%= form.text_field :name, id: 'name' %>
</div>
<div class="field">
<%= form.label :admission_number %>
<%= form.text_field :admission_number, id: 'number'%>
</div>
<div class="field">
<%= form.label :age %>
<%= form.number_field :age, id: 'age' %>
</div>
<div class="field">
<%= form.label :admission_date %>
<%= form.date_select :admission_date %>
</div>

<div class="actions">
<%= form.submit 'Save', class: 'btn btn-primary', :onclick => "return confirm('Please confirm:- '
+ 'Name: ' + document.getElementById('name').value + ', Admission Number: ' + document.getElementById('number').value + ', Age' + document.getElementById('age').value + '?')" %>
</div>
<% end %>

However, this will get clumped and confusing if the data attributes are very many. If you have more ideas on how to implement this, please feel free to email me.