Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.