gpt4 book ai didi

ruby-on-rails - 通过定义虚拟属性在 Rails 表单验证中获取 current_user

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:58 24 4
gpt4 key购买 nike

Rails 表单验证旨在最轻松地进入模型。但我需要确保当前用户具有提交帖子所需的权限,并且 current_user 变量只能在 Controller 和 View 中访问。

我在 similar question 中找到了这个答案:

You could define a :user_gold virtual attribute for Book, set it in the controller where you have access to current_user and then incorporate that into your Book validation.`

如何使用我的帖子和用户 Controller 进行设置,以便可以在模型中访问 current_user 变量?

解决方案:

正如@Deefour 的回答所指出的,从应用程序设计的角度来看,这整件事都是错误的。我对其进行了更改,因此除非条件为真,否则我的 View 不会呈现表单。

最佳答案

“类似问题”是说你可以做这样的事情

class YourModel < ActiveRecord::Base
attr_accessor :current_user

# ...
end

然后在你的 Controller Action 中你可以做类似的事情

@your_model = YourModel.find(params[:id])
@your_model.current_user = current_user
@your_model.assign_attributes(params[:your_model])

if @your_model.valid?
# ...

然后您可以在 YourModel 的验证方法中使用 self.current_user


注意 不过我认为这不是您应该做的,因为我认为这种“验证”不如“授权”。未经授权的用户甚至不应该能够获得您的操作的一部分,其中可以保存对 YourModel 实例的此类更新。


至于按要求与 Pundit 进行授权,您将在 app/policies/your_model.rb 中有一个文件

class YourModelPolicy < Struct.new(:user, :your_model)
def update?
user.some_privilege == true # change this to suit your needs, checking the "required privileges" you mention
end
end

在您的 ApplicationController 中包含 Pundit

class ApplicationController < ActionController::Base
include Pundit
# ...
end

然后,在您的 Controller 操作中,您可以简单地做

def update
@your_model = YourModel.find(params[:id])
authorize @your_model

# ...

authorize 方法将调用 YourModelPolicyupdate? 方法(它调用与您的操作相匹配的方法 + ? 默认情况下) 如果返回虚假值,将导致 403 错误。

关于ruby-on-rails - 通过定义虚拟属性在 Rails 表单验证中获取 current_user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14289550/

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