简体   繁体   English

如何在Rails中实施业务规则?

[英]How to implement business rules in Rails?

I have a set of business rules that I need to enforce, such as: 我有一组需要执行的业务规则,例如:

  1. If current_user is not "admin" then don't allow and give message "restricted access" 如果current_user不是“ admin”,则不允许并给出消息“受限访问”
  2. If question has been answered then don't allow another another answer and give message "question has already been answered" 如果问题已回答,则不允许其他回答,并提示“问题已回答”

Now, all these are basically: "if X is false then Y message". 现在,所有这些基本上都是:“如果X为假,则为Y消息”。

So, I made this method: 所以,我做了这个方法:

def evaluate_rules rules
  rules.each_pair do |state,message|
    if not (state == true)
      return false,message
    end
  end
  true
end

Meant to be called like this: 意思是这样的:

evaluate_rules { 
  (1==1) => "good", #rule will pass
  (1==2) => "bad" #rule will fail
}

But, I get the error syntax error, unexpected tASSOC (SyntaxError) for the (1==1) and (1==2) hash keys. 但是,我得到了错误syntax error, unexpected tASSOC (SyntaxError) (1==1)(1==2)哈希键syntax error, unexpected tASSOC (SyntaxError)

How to put values of true/false into a hash key? 如何将true / false值放入哈希键?

Also, I can't help but think someone may have solved this "rules" problem before, any leads? 另外,我不禁要以为有人可能已经解决了这个“规则”问题,有什么线索吗?

UPDATE 更新

Fixed. 固定。 Sometimes Ruby frustrates me. 有时候露比让我感到沮丧。 The call should be like this: 调用应如下所示:

evaluate_rules Hash.new({ 
  (1==1) => "good", #rule will pass
  (1==2) => "bad" #rule will fail
})

Looks a bit ugly but works 看起来有点难看但是可以用

There are several ways to accomplish this, but the best is probably to use the built-in Rails validators. 有多种方法可以完成此操作,但是最好的方法是使用内置的Rails验证器。 These are setup to do pretty much what you're describing. 这些设置可以完成您所描述的内容。 In each model, you can create validations, that then add messages to an errors array if validation fails. 在每个模型中,您可以创建验证,然后在验证失败时将消息添加到错误数组。 There are a number of built in validations, and the ability to build completely custom ones. 有许多内置的验证,并且可以构建完全自定义的验证。 This is the approach I would take to the two use cases listed above. 这是我要针对上面列出的两个用例采取的方法。

Some examples here: http://omgbloglol.com/post/392895742/improved-validations-in-rails-3 此处的一些示例: http : //omgbloglol.com/post/392895742/improved-validations-in-rails-3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM