强参数:如何使用条件允许参数 [英] Strong Parameters: How to permit parameters using conditions

查看:31
本文介绍了强参数:如何使用条件允许参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想根据当前用户的角色允许某些参数.

I wan't to permit certain parameters depending on the current user's role.

例如:如果用户是管理员,则只允许 role 属性.

E.g: only permit the role attribute if the user is an administrator.

这可能吗?

推荐答案

是的,这是可能的.

你可以这样做:

def user_params
  # List of common params
  list_params_allowed = [:email, :title, :last_name, :first_name, :phone]
  # Add the params only for admin
  list_params_allowed << :role if current_user.admin?
  params.require(:user).permit(list_params_allowed)
end

这样,如果以后有新的参数,只需添加一个列表(避免错误).

This way, if later you have new params, you only have to add in one list (avoids error).

如果您要为管理员添加多个参数,您可以这样做:

If you have more than one param to add for the admin, you can do this like this :

list_params_allowed << :role << other_param << another_param if current_user.admin?

希望对您有所帮助.

这篇关于强参数:如何使用条件允许参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆