advice on validation

Hello all,

Currently I am having a controller with several actions. A client perform some kind of wizard to create a persisted object (ActiveRecord). So step1, step2, step3 and finally saves the object to DB in step 4. Each step takes ask for a couple of info from the client which is part of the end persisted object. Basically it follows the logic below:

step1 -> name, address step2 -> validate address against a third party site step3 -> email and other info step4 -> saves all the above information to DB

Each step correspond to an action. All the 4 steps are in the same controller. Step2 depends on step1 thus the wizard type process.

I built the above and it is working like a charm. However, I am wondering about validation. I want to use ActiveRecord validation. What would you suggest? Javascript for each step + ACtiveRecord validation at step4 that would redirect to an "edit" page which would contain all 4 steps in 1 "edit" action? I will probably go for that but was wondering if anybody had any suggestion to produce a validation mechanism per step.

Thanks, Carl

def my_action

return unless request.post?

case params[:stage]

    when '1'

        session[:my_record] = Model.new(params[:model])

        if not session[:my_record].valid?     

            flash[:notice] = "Invalid name" if session[:my_record].errors.invalid?(:name)
            flash[:notice] = "Invalid address" if session[:my_record].errors.invalid?(:address)

        end

    when '2'

        return unless session[:my_record]

        if not MyThirdPartyValidation.valid_something(params[:model][:something])
            session[:my_record].errors.add :something, "is invalid."

        else
            session[:my_record][:something] = params[:model][:something]
        end

end

end

No perfect as it’ll validates every column for each stage you call valid?, I’m not sure of a better method in my current tired state :slight_smile:

Be sure your code can handle a malicious user skipping stages, i.e the return unless session[:my_record] stuff.

Validate using AR and the :if option. E.g.,

validates_presence_of :foo, :if => Proc.new(|wizard| wizard.step > 1)

Note that the wizard parameter passed into the block is the instance of your model class, so the model itself needs to understand what step it is on.

HTH

Carl-Gustaf Harroch wrote: