Skip to content

Building objects without saving to the database

Seth Fitzsimmons edited this page Feb 14, 2015 · 7 revisions

Problem: I want to use multi step forms though I don't want incomplete records saved to the database every time a user does not complete the form.

Solution: One way to solve this issue is to save your record to the session store and retrieve it when you're ready to save it.

Here is an example:

class BookStepsController < ApplicationController
  include Wicked::Wizard
  steps :name, :author
  
  def show
    case step
    when :name
      @book = Book.new
      session[:book] = nil
    else
      @book = Book.new(session[:book])
    end
    render_wizard
  end
  
  def update
    case step
    when :name
      @book = Book.new(book_params)
      session[:book] = @book.attributes
      redirect_to next_wizard_path
    when :data
      session[:book] = session[:book].merge(params[:book])
      @book = Book.new(session[:book])
      @book.save
      redirect_to book_path(@book)
    end
  end
  
  private

  def finish_wizard_path
    book_path(@book)
  end

  def book_params
    params.require(:book).permit(:name, :author)
  end
end

Note: If you get a ActionDispatch::Cookies::CookieOverflow error you have reached your 4k limit in the session store. To fix this you'll need to use the active record store rather than the cookie store:

Gemfile

gem 'activerecord-session_store', github: 'rails/activerecord-session_store'

config/initializers/session_store

Rails.application.config.session_store :active_record_store