[英]Strong Parameters: How to permit parameters using conditions
I wan't to permit certain parameters depending on the current user's role.我不想根据当前用户的角色允许某些参数。
Eg: only permit the role
attribute if the user is an administrator.例如:如果用户是管理员,则只允许role
属性。
Is this possible?这可能吗?
Yes, it's possible. 是的,这是可能的。
You can do something like this : 你可以这样做:
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?
Hope this help. 希望这有帮助。
You can simply do the following:您可以简单地执行以下操作:
def post_params
allowed = [:name, :age]
conditional = Some_Condition_Applies ? [:title, :description] : []
params_list = allowed + conditional
params.require(:post).permit(params_list)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.