将业务规则移动到模型中 [英] Moving business rules into model

查看:144
本文介绍了将业务规则移动到模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问过一个问题,引起了一些很好的反应。

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

,因此:

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

我从before_save回调函数中调用。

I am calling that from a before_save callback.

默认情况下,consulted_legal和consulted_marketing属性都设置为false而不是null,这就是为什么我在这里测试== false或true,而不是询问

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?

逻辑似乎不工作。如果我检查对象,状态没有被设置为任何东西,永远。任何人都可以察觉为什么会发生这种情况?例如

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

推荐答案

而不是 status = 请尝试 self.status = 。我发现我需要使用 self。来更改模型中的模型属性。

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

更好的是 errors.empty?而不是 true ,所以如果你使用 errors.add_to_base ,您的 set_status 方法就可以中止保存。

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.

编辑

您还可以查看
acts_as_state_machine 。它看起来像一个插件,正是你在做什么。


You may also want to check out acts_as_state_machine. It looks like a plugin for exactly what you're doing.

这篇关于将业务规则移动到模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆