Search code examples
ruby-on-rails-3authenticationstrong-parameters

Work-around for multiple access cases with strong_parameters


I have an app where the User is allowed to access their :name, :lastname, :email attributes only once - during the initial account setup. After this (for security reasons) they are not allowed to change either of these attributes; only an Admin can.

def user_params
    if current_user && current_user.admin?
      params.require(:user).permit(:name,
                                :surname,
                                :admin)
    else
      params.require(:user).permit()
    end
end

Then during user.create I allow the User to complete the registration form and access these protected attributes, but during user.update, only an Admin can change that information.

Since user_params is being called for each method (new, create, edit, update, show, destroy), it won't allow the user to write these attributes and set up an account if I restrict access to these attributes to Admins only after account creation/verification.

Any ideas on how to solve this problem? Or am I just missing something about strong_parameters?


Solution

  • user_params is just a helper method so you don't have to repeat the same code in all of the actions. If the code in create is different from the code in update, just create another helper method:

    def user_create_params
      if current_user && current_user.admin?
        params.require(:user).permit(:name, :surname, :admin)
      else
        params.require(:user).permit(:name, :surname)
      end
    end
    
    def user_update_params
      if current_user && current_user.admin?
        params.require(:user).permit(:name, :surname, :admin)
      else
        params.require(:user).permit()
      end
    end