views:

135

answers:

2

I asked a question earlier which elicited some great responses.

Here's the earlier question

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

+6  A: 

Instead of status = try self.status =. I've found that I needed to use self. to change a model's attribute within the model.

It's also much better to have errors.empty? at the end instead of true, so if you ever use errors.add_to_base in the future, your set_status method 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.

Samuel
+1  A: 

Are you setting the parameters from user input?

If they're not defined as boolean database columns, then you'll be assigning a string to them, which will never be equal to true.

Jon Wood
I suspect he has those columns and that's were they were coming from in the controller.
Samuel
indeed. thanks both. will try to amend and see what happens.
The Pied Pipes