我正在我的 Rails 应用程序中运行 Pundit 以进行授权。我似乎已经掌握了这一切,但想知道如何将编辑或更新操作限制到某个字段。
例如,用户可以编辑他们的 user.first_name、user.mobile 或 user.birthday 等,但不能编辑他们的 user.role。基本上我的逻辑是,让用户编辑任何装饰性的东西,但如果它是功能性的,则不允许。
这些字段应该只能由具有“super_admin”角色的用户编辑(我在 user.rb 上使用如下方法进行了设置)。
def super_admin?
role == "super admin"
end
def account?
role == "account"
end
def segment?
role == "segment"
end
def sales?
role == "sale"
end
def regional?
role == "regional"
end
def national?
role == "national"
end
def global?
role == "global"
end
我几乎有一个干净的石板
user_policy.rb
更新和编辑操作是默认的文件 def update?
false
end
def edit?
update?
end
也许我对此的想法完全错误,应该只包装一个 user.super_admin?用户显示页面上的角色字段周围的 if 语句,但如果我只是为了安全而使用该策略,这感觉是错误的。
最佳答案
使用 Pundit 的 permit_attributes 助手,它在 gem 的 README 页面中描述:https://github.com/elabs/pundit
# app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy
def permitted_attributes
if user.admin? || user.owner_of?(post)
[:title, :body, :tag_list]
else
[:tag_list]
end
end
end
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def update
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
redirect_to @post
else
render :edit
end
end
private
def post_params
params.require(:post).permit(policy(@post).permitted_attributes)
end
end
关于ruby-on-rails - 授权用户在 Rails 中使用 Pundit 编辑特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29138825/