Fabrizio Bertoglio Fabrizio Bertoglio - 9 months ago 48
Ruby Question

Rails - strong params removing empty fields from nested attributes

I have been working on this line of code for three days.
I have the following strong params:

def location_params
params.require(:location).permit(:country, {:ads_attributes => [:remote, :days]})
end


The method param_clean will delete from the location_params the empty fields, but it will not work with the nested :ads_attributes.
The main reason is that param_clean can only be called on location_params that has class ActiveController::Parameters. I can not call on v the method param_clean

def param_clean
location_params.delete_if{ |k, v| v.empty? or v.instance_of?(ActionController::Parameters) && v.param_clean.empty? }
end


I receive the following error

undefined method `param_clean' for #<ActionController::Parameters:0x007f..>


This is the value of location_params

<ActionController::Parameters {"country"=>"", "ads_attributes"=><ActionController::Parameters {"remote"=>"0", "days"=>""} permitted: true>} permitted: true>


This is the value of
v
variable when the error is triggered

<ActionController::Parameters {"remote"=>"0", "days"=>""} permitted: true>

v.class => ActionController::Parameters


The method does not work with the nested parameters.
Thanks a lot for your help

Best Regards
Fabrizio

Answer Source

The problem is that the param_clean method is not defined in ActionController::Parameters class. So, you have to change your approach, by either:

  • Extending ActionController::Parameters to include the method (not that I would recommend it).
  • Refactor the method. One way to do it would be as follows:

    def param_clean(_params)
      _params.delete_if do |k, v|
        if v.instance_of?(ActionController::Parameters)
          param_clean(v)
        end
        v.empty?
      end
    end
    
    # how to use it
    param_clean(location_params)