Moving business rules into model

别说谁变了你拦得住时间么 提交于 2019-12-13 00:29:24

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/473325/moving-business-rules-into-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!