【问题标题】:Rails pundit scope does not return from or blockRails 权威范围不返回或阻塞
【发布时间】:2021-04-20 23:08:22
【问题描述】:

在我的应用中,我想阻止用户再次参加法律考试。为此,我使用具有以下政策的权威人士授权:

class TestResultPolicy < ApplicationPolicy
  def new?
    !passed? || validation_not_finished?
  end

  private

  def passed?
    user.test_results.where.not(test_result: 'passed').any?
  end
end

我在下面的控制器中使用:

class TestResultsController < ApplicationController
  before_action :randomize_questions, only: %i[new create]

  def new
    @test_result = TestResult.new
    authorize @test_result
  end

  def create
    #some actions
  end

问题是当用户已经通过测试时,他仍然有能力参加另一个测试(可以访问test_results_path)。如果我离开!passed?,一切都会正常工作,但如果我添加或条件|| validation_not_finished?,它将使整个块为真而不是返回假,并跳过||之后的所有内容?

【问题讨论】:

    标签: ruby-on-rails ruby pundit


    【解决方案1】:

    || => 称为逻辑或运算符。如果两个操作数中的任何一个为真,则条件为真。

    > false || false
    => false
    > false || true
    => true
    > true || false
    => true
    > true || true
    => true
    

    当用户测试失败时,你可以显式返回false,这样它就会跳过对validation_not_finished?的检查

    class TestResultPolicy < ApplicationPolicy
      def new?
        return false if failed?
        validation_not_finished?
      end
    
      private
    
      def failed?
        user.test_results.where.not(test_result: 'passed').any?
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-25
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多