Ask Your Question
1

How can Rails be configured to allow one key and require another using strong parameters?

asked 2023-02-24 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-09-13 10:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-02-24 11:00:00 +0000

Seen: 9 times

Last updated: Sep 13 '21