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...
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...
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/
You're falling victim to a common beginner misconception.
The role of
ActionController::Parameters#requireis 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:
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.