Rails strong params, require one key and permit another

571 views Asked by At

I'm posting:

{'a': 1, 'b': 2}

where key a is always required and key b is optional. How do I require a and permit b using Rails strong params syntax? params.require(:a).permit(:b) doesn't work...

2

There are 2 answers

4
max On

You're falling victim to a common beginner misconception.

The role of ActionController::Parameters#require is not to validate the presence of parameters - it's to bail early if the structure of the parameters doesn't match the expected input at all. Validations are typically done by the model in Rails.

For example when you have the typical Rails parameters whitelist:

def thing_parameters
  params.require(:thing)
        .permit(:foo, :bar, :baz)
end

There is no meaning in continuing to process the request and trying to update/create a thing if params[:thing] is nil. Therefore we bail early and a return a 400 Bad Request status code.

0
rnwed_user On

I believe that you can solve with other way, using dry validation

require 'dry-validation'

class TableContract < Dry::Validation::Contract
  params do
    required(:a).filled(:bool)

    optional(:b).maybe(:string)
  end
end

now you can use that contract from your controller

TableContract.new.call( a: params[:a], b: params[:b])

more information: https://dry-rb.org/gems/dry-validation/1.8/