Rails 与运营商从头开始授权

Rails authorization from scratch with operators

所以我根据 Ryan Bates 的 railscast 从头开始​​授权。

我认为我面临的问题是在这部分代码中

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

我想说的是,如果操作是 create OR 操作是 update(所以它们中的任何一个)AND obj.has_accepted_acceptance? 它应该 return false,但它 return 是真的,除非我删除 || action == 'update' 部分代码。只有这样它才能按预期工作。

那么是不是运营商的问题? 预先感谢您的宝贵时间!

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

尝试对您的条件进行分组:

if (action == 'create' || action == 'update') && obj.has_accepted_acceptance?

您可以使用 ActiveSupport .in? 将第一个从两个子句转换为一个:

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

普通旧 ruby 中的相同内容是:

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