I asked a question earlier which elicited some great responses.
On the back of some advice given there, I’ve tried moving the following controller logic
if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1 @concept.attributes = {:status => 'Awaiting Compliance Approval'} elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1 @concept.attributes = {:status => 'Awaiting Marketing Approval'} elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0 @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'} else @concept.attributes = {:status => 'Pending Approval'} end
into the model, as so:
def set_status if status.blank? if (consulted_legal == true) && (consulted_marketing == true) status = 'Pending Approval' elsif (consulted_legal == true) && (consulted_marketing == false) status = 'Awaiting Marketing Approval' elsif (consulted_legal == false) && (consulted_marketing == true) status = 'Awaiting Legal Approval' elsif (consulted_legal == false) && (consulted_marketing == false) status = 'Awaiting Marketing & Legal Approval' end end true # Needs to return true for the update to go through end
I am calling that from a before_save callback.
As a default, both the consulted_legal and consulted_marketing attributes are set to false and not null, which is why I am testing for == false or true here, instead of asking
if consulted_legal?
for instance.
However, this logic doesn’t seem to be working. If I inspect the object, status is not being set to anything, ever. Can anyone spot why this might be happening? Have I got how attributes are accessed wrong in models, for instance?
TIA
Instead of
status =tryself.status =. I’ve found that I needed to useself.to change a model’s attribute within the model.It’s also much better to have
errors.empty?at the end instead oftrue, so if you ever useerrors.add_to_basein the future, yourset_statusmethod is ready to abort a save.Edit:
You may also want to check out
acts_as_state_machine. It looks like a plugin for exactly what you’re doing.