#16 Complex Strong Parameters


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


application_controller.rb    def permitted_params
      @permitted_params ||= Params::PermittedParams.new(params, current_user)
    helper_method :permitted_params
app/strong_params/permitted_params.rb    class PermittedParams < Struct.new(:params, :current_user)
      include Params::User
app/strong_params/params/user.rb    module Params
      module User
        def user

        def user_attributes
          [].tap do |attributes|
            attributes << :first_name
            attributes << :last_name
            attributes << :role if current_user.admin?
            attributes << :email
            attributes << :profile_image
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 %>
kobaltz PRO said about 4 years ago on Complex Strong Parameters :

They are very similar. However, not every application needs pundit. Sometimes a simple role based authorization is sufficient. While I love using a number of gems, it is sometimes better to roll your own solution as it will be something that you can better maintain. Regardless, this episode is meant to show the extraction of strong parameters and allow them to do something a bit more complex. I'll be covering pundit in depth in a future episode.

Personally, I try not to rely on before_actions for security. In some instances, it makes sense. In your example, I would have something similar in an admin namespace. However, I would still build out the proper authorizations in the admin namespace as it would allow for easier expansion down the road. For example, if I have two roles, admin and user, but later want to add a maintainer with certain access within the admin namespace, the framework is already created for the admin and would need to be expanded for a maintainer role.

Overall, I still prefer the extraction of the strong parameters as I have displayed as it allows for the code to be better compartmentalized. However, when compared to Pundit's strong params approach, it is most likely a matter of preference.

mabel said almost 4 years ago on Complex Strong Parameters :

Really useful pattern. Tnx!

Login to Comment