Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Confirmation Page for ActiveRecord Object Creation

Using Ruby on Rails I want a confirmation page before creating an ActiveRecord object. The user will see a preview of the item they are creating before submitting and the object being saved in the database

A common pattern;

  • User visits /entry/new
  • User enters details and clicks submit
  • User is redirected to /entry/confirm which displays the entry and clicks submit or edit to correct mistakes
  • Object is saved

How would you implement it?

like image 846
mmcbeath Avatar asked Jan 15 '09 01:01

mmcbeath


2 Answers

Another option to solve this issue adding by a virtual confirmation attribute to your model. This way, there is no need to create a separate action for this:


class MyRecord < ActiveRecord::Base
  attr_accessor :confirmation
  validates_acceptance_of :confirmation, :on => :create
end

Now, your new object will not save correctly because the validation will fail on the confirmation field. You can detect this situation and present something like this:


<% form_for(@my_record) do |form| %>
  ...
  <%= form.check_box :confirmation %> Really create this record.
  <%= submit_tag('Confirm') %>
<% end %>
like image 120
wvanbergen Avatar answered Sep 21 '22 09:09

wvanbergen


I would probably add a "preview" action to the routes.rb file for that model:

map.resource :objects, :new => { :preview => :post }

You would get to this preview action by POSTing the preview_object_url named route. You would need to essentially create the Object in the same way you would in your create action, like this:

def preview
  @object = Object.new(params[:object])
end

This page would then POST to the create action, which would then create the Object. It's pretty straight forward.

http://api.rubyonrails.org/classes/ActionController/Resources.html

like image 24
Josh Delsman Avatar answered Sep 23 '22 09:09

Josh Delsman