fabOnReact
fabOnReact

Reputation: 5942

Rails - Calling a Method on Action Controller Parameters

I am trying to implement the method found in the below discussion to delete from my my strong params all fields that are blank.

class Hash
  def delete_blank
    delete_if{|k, v| v.empty? or v.instance_of?(Hash) && v.delete_blank.empty?}
  end
end

p hash.delete_blank
# => {"y"=>"content"}

How to recursively remove all keys with empty values from (YAML) hash?

This are location_params from which I want to remove the empty fields:

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

The following error triggers when I call the following delete_blank method on location_params

undefined method "delete_blank" for #<ActionController::Parameters:0x007.....>

My opinion is that I have to modify the Hash Class in my Rails project, but I do not know how to do it and I think it may not be the best solution.

Thanks a lot for your help Fabrizio

Upvotes: 2

Views: 1178

Answers (1)

spickermann
spickermann

Reputation: 107097

The structure returned by Rails params method looks like a Hash, but actually it is an instance of ActionController::Parameters.

Since delete_blank is not defined on ActionController::Parameters, but on Hash you get this error: undefined method "delete_blank" for #<ActionController::Parameters...

You have two options:

A) Define the method on ActionController::Parameters:

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

Or B) translate the instance of ActionController::Parameters into a Hash, call the method and translate it back:

ActionController::Parameters.new(params.to_h.delete_blank).permit!

Upvotes: 4

Related Questions