gpt4 book ai didi

ruby-on-rails - 如何将 before_action 与 :unless and params 一起使用

转载 作者:行者123 更新时间:2023-12-02 17:08:37 25 4
gpt4 key购买 nike

我有一个我构建的授权模块来授权用户操作。一切都很好,除了现在如果请求页面的用户是当前用户我想跳过该操作。该资源嵌套在 user 下面,因此将 :user_id 作为参数的一部分传递。

据我所知,执行此操作的最简单方法是使用 lambda,但我似乎无法访问从前过滤器传递的参数。

这是我的 Controller

class Certifications::FitnessController < ApplicationController
prepend_before_action :authenticate_user!
before_action :authorize, unless: -> { params[:user_id] == current_user.id }
end

问题是 :authorize before_action 从未被调用,因此允许所有操作(我假设是因为 unless 语句总是评估为真),但我无法检查发生了什么因为如果我在那里停止执行,那里似乎没有参数(我认为这应该让它总是评估为假,而不是真的)。​​

如果有人能告诉我我做错了什么或更好的实现方式,我将不胜感激。

编辑:如果您将参数转换为整数以匹配 current_user.id,则上面的代码实际上有效

before_action :authorize, unless: -> { params[:user_id].to_i == current_user.id }

最佳答案

  before_action do |controller|
unless params[:user_id].to_i == current_user.id
controller.authorize
end
end

或者你可以这样做:-

before_action :authorize

def authorize
unless params[:user_id].to_i == current_user.id
#do your stuff..
end
end

第二选择

before_action :authorize, unless: -> { params[:user_id].to_i == current_user.id }

关于ruby-on-rails - 如何将 before_action 与 :unless and params 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50466056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com