首页 > 解决方案 > RoR 更新字段 - 基于用户角色的金额限制?

问题描述

我正在考虑实现逻辑的最佳方法如下:

用户可以根据他们的角色使用数量更新属性。

例子:

@some_user = User.first.points => 10

if current_user.admin?最多可以加 +100 分@some_user

if current_user.cs_staff?最多可加 +50 分。

if current_user.junior_cs_staff?最多可加 +10 分。

你将如何验证它?自定义模型验证或更好地在 Pundit 政策中指定?(我正在使用 Pundit)。

标签: ruby-on-railsrubyvalidationruby-on-rails-5

解决方案


您可以在模型中添加自定义验证方法,如下所示

validate :validate_user

def validate_user
  if current_user.junior_cs_staff? && points > 10
    errors.add(:points, "You can't add more then 10 points")
  elsif current_user.cs_staff? && points > 50
    errors.add(:points, "You can't add more then 50 points")
  elsif current_user.admin? && points > 100
    errors.add(:points, "You can't add more then 100 points")
  end
end

但我的建议是在 Junior_cs_staff 登录时仅显示 +10 按钮,在 cs_staf 登录时仅显示 +50 点按钮,在管理员登录时显示 +100 按钮。

您可以添加此角色条件以查看


推荐阅读