views:

1430

answers:

4

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?

A: 

I'm not sure how to do this (RoR is new to me) but you could just specify the action for /new as /confirm, and then it calls create.

Right?

Rob Elsner
+2  A: 

A few options

1- store the object you want to create in the session until you hit the confirm page, then just save it

2- pass around the object w/ each Post/submit from new -> details -> confirm

I would probably go with 2, since I am not prone to saving state with the session.

Bill
+4  A: 

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 %>
wvanbergen
+2  A: 

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

Josh