views:

161

answers:

1

I have a form that I'm trying to create which is broken up into sections. Each section saves a little bit of info to that table and then moves on to the next page. I'm trying to figure out the best way to validate the data for each section in the model. I was to use something like validates_presence_of, but that expects all of the data that is being validated will be available upon saving... In my case, the entire table won't be filled out until they're done going through each section.

What's the best way to do this if there is a way?

+5  A: 

You can make validations conditional with the :if or :unless options. If you add a "step" column to your table you can use this to validate the model along the way.

class Item < ActiveRecord::Base
  validates_presence_of :name # step 1
  validates_presence_of :category_id, :if => Proc.new { |i| i.step >= 2 } # step 2
  validates_presence_of :description, :if => Proc.new { |i| i.step >= 3 } # step 3
end

You can then increment the step count each time in your controller.

def update
  @item = Item.find(params[:id])
  @item.step += 1
  if @item.update_attributes(params[:item])
    # ...
  end
end

You may also want to consider using a state machine.

ryanb