Rails 4 - pundit - 如何编写 if 语句来检查用户权限

2024-03-03

我正在尝试学习如何在我的 Rails 4 应用程序中使用 pundit。

我有一个潜在的使用政策。潜在用途表有一个名为:user_id 的属性。

我希望允许用户更新创建实例的实例。我正在尝试找出如何使更新操作发挥作用。

我当前的尝试如下所示。

class PotentialUsePolicy < ApplicationPolicy

    attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end


    def index?
        true if user.is_admin?
    end

    def show?
        true

    end

    def new?
      true
  end

    def create?
        new?
    end

    def update?
        if @user.id == @potential_use.user_id

        # if user.id == potential_use.user_id
            true
        else
            false
        end
    end

    def destroy?
        update?
    end

    def edit?
                true
    end

    def potential_use
        record
    end 

end

当我尝试这些时,我不断收到错误消息:

undefined method `user_id' for nil:NilClass

我不明白为什么会收到这条消息。当我查看控制台时,我可以看到一个具有用户 ID 的条目。

p = PotentialUse.where(project_id: 26)
  PotentialUse Load (0.5ms)  SELECT "potential_uses".* FROM "potential_uses" WHERE "potential_uses"."project_id" = $1  [["project_id", 26]]
 => #<ActiveRecord::Relation [#<PotentialUse id: 9, comment: "adsfsfdadfasdddxxddbbdd", project_id: 26, created_at: "2016-08-18 23:16:06", updated_at: "2016-08-24 01:06:00", user_id: 1, private_comment: false>]> 
2.3.0p0 :016 > 

当我查看视图时(不尝试使用 pundit 策略),页面会呈现所有正确的内容,包括用户名(通过 user_id 访问)。

我的潜在使用控制器中的更新操作有:

def update
    authorize @potential_use
    respond_to do |format|
      if @potential_use.update(potential_use_params)
        format.html { redirect_to @project, notice: 'Potential use was successfully updated.' }
        format.json { render :show, status: :ok, location: @potential_use }
      else
        format.html { render @project }
        format.json { render json: @potential_use.errors, status: :unprocessable_entity }
      end
    end
  end

谁能看到我做错了什么吗?


要检查用户是否有权从视图中对策略执行操作:

<% if policy(@post).update? %>
  <%= link_to "Edit post", edit_post_path(@post) %>
<% end %>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 4 - pundit - 如何编写 if 语句来检查用户权限 的相关文章

随机推荐