Rails从头授权与运营商 - Rails authorization from scratch with operators

- 此内容更新于:2016-02-01
主题:

所以我让授权基于瑞安贝茨的railscast从头开始。我想我面临的问题是在这部分的代码我想说的是,如果行动或行动(所以他们中的任何一个),它应该返回false,但它返回true,除非我消除代码的一部分。只有这样它按预期的方式工作。那么,运营商的问题吗?提前感谢您的时间!

原文:

So I'm making authorization from scratch based on Ryan Bates' railscast.

I figured the problem i'm facing is in this part of code

action == 'create' || action == 'update'

What I want to say is that if the action is create OR action is update (so either of them) AND obj.has_accepted_acceptance? it should return false, but it returns true unless I eliminate || action == 'update' part of code. only then it works as intended.

So is the problem with the operators? Thank you in advance for your time!

class Permission < Struct.new(:user)

  def allow?(controller, action, obj = nil)
    if controller == "acceptances"
      if action == 'create' || action == 'update' && obj.has_accepted_acceptance?
        return false
      end
    end
    return true 
  end
end
解决方案:
试着分组你条件:
原文:

Try grouping your conditions:

if (action == 'create' || action == 'update') && obj.has_accepted_acceptance?
解决方案:
您可以使用ActiveSupport这样转换第一个从两个条款:在普通的ruby是:
原文:

You can use the ActiveSupport .in? to convert the first from two clauses to one:

if action.in?(%w[create update]) && obj.has_accepted_acceptance?

The same in plain old ruby would be:

if %w[create update].includes?(action) && obj.has_accepted_acceptance?