Complex Strong Parameters

Episode #16 by Teacher's Avatar David Kimura

Summary

Make your strong parameters do more by extracting the logic in order to maximize the ability and security of your application.
rails security parameters 4:52

Resources

Summary

# application_controller.rb
    def permitted_params
      @permitted_params ||= Params::PermittedParams.new(params, current_user)
    end
    helper_method :permitted_params

# app/strong_params/permitted_params.rb
    class PermittedParams < Struct.new(:params, :current_user)
      include Params::User
    end

# app/strong_params/params/user.rb
    module Params
      module User
        def user
          params.require(:user).permit(*user_attributes)
        end

        def user_attributes
          [].tap do |attributes|
            attributes << :first_name
            attributes << :last_name
            attributes << :role if current_user.admin?
            attributes << :email
            attributes << :profile_image
          end
        end
      end
    end

# users_controller.rb
    @user.update(permitted_params.user)

# _form.html.erb
     <%= f.input :role, collection: User.roles.keys.map { |k| [k.titleize,k] } if permitted_params.user_attributes.include? :role %>