ruby-on-rails - 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)。
解决方案
您可以在模型中添加自定义验证方法,如下所示
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 按钮。
您可以添加此角色条件以查看
推荐阅读
- javascript - 来自子异步回调函数的错误句柄
- selenium-webdriver - 如何在边缘铬浏览器上使用 capybara 运行 selenium webdriver 测试?
- php - 我似乎无法将复选框值添加到 db
- typescript - 如何创建每个值的类型取决于键的查找?
- javascript - 如何防止 iOS Safari 聚焦新元素?
- python - 如何使用 termcolor 为 pandas 数据框中的文本着色
- reactjs - 如何显示更新的用户信息?
- c++ - How can I use a function to write LCD text? - Arduino
- python - 如何删除python目录?
- android - 用于retrofit2的Android JUnit测试给出空指针异常