To allow one key and require another using strong parameters in Rails, you can use the permit
method with the :require
option to require a parameter and the :allow
option to allow a parameter. Here's an example:
def person_params
params.require(:person).permit(:name, :email, :phone).tap do |whitelisted|
whitelist[:phone] = params[:person][:phone] if params[:person][:phone].present?
end
end
In this example, we're requiring the :person
parameter and allowing :name
, :email
, and :phone
. We're also using the tap
method to modify the whitelisted
parameters hash to include the :phone
parameter only if it's present in the params
hash.
With this configuration, the :name
and :email
parameters are allowed but not required, while the :phone
parameter is both allowed and required.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-02-24 11:00:00 +0000
Seen: 9 times
Last updated: Sep 13 '21
Why am I not getting a response when making a URL call in ASP.NET Web API?
How to provide parameters to machine learning model objects?
How can you obtain several parameters using a single GET request?
What is the process of creating global parameters in OpenAPI?
How can I include custom header parameters in request details when using swagger?
What are some queries regarding the simulation of pic_poll_read in kvm?
How to pass parameter correctly from @Url.Action to method?
Explain what the main file is, but do not give any details about the parameters it contains.
How can I conceal parameters in the request body according to the schema in Swagger?