Reputation: 673
I have a form wizard that validates certain fields based on what the objects current step is. The problem I am having is that since the current_step is a part of the model, I cannot update the current_step without the validation failing. Let me show you what i mean.
class Goal< ActiveRecord::Base
validates_presence_of :school_id, if: 'current_step == "school"'
validates_presence_of :class_id, if: 'current_step == "class"'
def update
...
if @user.update(params)
#this evaluates to true since the current_step == "school", and school_id is present
@user.update(current_step: @user.next_step)
#I am unable to update the current_step, because current_step == "class" now, and the class_id is missing
redirect_to registration_path(@user)
else
render "show"
end
end
end
So basically, what is the best way to update the current_step of the object, without it triggering validation? Or is there a better way to do this? I have a feeling that I need to move the current_step object out of the model and into a session, but I would like to keep it attached to the model if possible and clean.
Upvotes: 0
Views: 276
Reputation: 717
You can do something as simple as:
@user.update_attribute(:current_step, @user.next_step)
This will not trigger validations. Or you can push it into params hash like this:
params[:user][:current_step] = @user.next_step
and then do update:
@user.update(params)
This way you will limit yourself with 1 mysql query
An alternative for this is to store current_step in the session, if you want to look at it.
There is a nice rails cast on that: http://railscasts.com/episodes/217-multistep-forms
Upvotes: 1