Rodrigo Vasconcelos
Rodrigo Vasconcelos

Reputation: 1290

Hanami parameters whitelisting

Following the hanami docs, in order to block a admin parameter inside an action, I can use the following configuration:

params do
  required(:email).filled

  required(:address).schema do
    required(:country).filled
  end
end

def call(params)
  puts params[:email]             # => "[email protected]"
  puts params[:address][:country] # => "Italy"
  puts params[:admin]             # => nil
end 

But this does not work for nested parameters, i.e.:

params do
  required(:email).filled

  required(:address).schema do
    required(:country).filled
  end
end

def call(params)
  puts params[:email]             # => "[email protected]"
  puts params[:address]           # => { country: "Italy", admin: true }
  puts params[:address][:admin]   # => true
end 

I was able to solve this by using select to filter out the undesirable parameters with a private method, but this does not seems like the Hanami way. What would be the proper way to do this whitelisting of nested parameters?

Upvotes: 1

Views: 216

Answers (1)

Danny Santos
Danny Santos

Reputation: 1160

I have never had this issue when using Hanami Validations. Within the app directory there should be a validations folder which should have the same directory structure as your controllers, views, templates etc. Your validation file should look something like this:

# apps/web/validations/users/create.rb

module Web
  module Validations
    module Users
      class Create < Web::Action::Params
        predicates Web::Validations::CommonPredicates

        validations do
          required(:email).filled

          required(:address).schema do
            required(:country).filled
          end
        end
      end
    end
  end
end

And then your controller should set the params to be filtered through the validation:

module Web
  module Controllers
    module Users
      class Create
        include Web::Action

        params Web::Validations::Users::Create

        def call(params); end
      end
    end
  end
end

Upvotes: 1

Related Questions