Strong Parameters: How to permit parameters using conditions

后端 未结 1 748
北恋
北恋 2021-02-06 03:28

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

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

Is

1条回答
  •  孤独总比滥情好
    2021-02-06 03:59

    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.

    0 讨论(0)
提交回复
热议问题