Search code examples
ruby-on-railsstrong-parameters

How do I allow all parameters even if they are blank?


I have the following:

def index
  @dealFilter = DealFilter.new params[:deal_filter].permit(deal_filter: {})

It works when parameters are given, but not when they are missing. It gives undefined method ``permit' for nil:NilClass Did you mean? print error. I would like it to work in both cases.

  • I tried params[:deal_filter] but it complained about ActiveModel::ForbiddenAttributesError.
  • I tried params.permit(deal_filter: {}) but it said unknown attribute 'deal_filter' for DealFilter..
  • I tried params.permit(:deal_filter) but it ignores the parameter values then: Unpermitted parameters: utf8, deal_filter, commit.

Solution

  • If params is blank, we need to set a default value for it using fetch:

    params.fetch(:deal_filter, {}).permit(:some_params)

    so that params[:deal_filter] will be {} when it is missing.

    From your errors, the final code should be:

    params.fetch(:deal_filter, {}).permit(:min, :max, :sector_id)