When a user submits a form and leaves certain fields blank, they get saved as blank in the DB. I would like to iterate through the params[:user] collection (for example) an
A good gem for handling this in the model: https://github.com/rmm5t/strip_attributes
It defines a before_validation
hook that trims whitespaces and sets empty strings to nil.
If you know which attributes you want to encode blanks as nils for you can use the following attribute setter override:
def colour=(colour)
super(colour.blank? ? nil : colour)
end
A bit bulky if you have a lot of attributes to cover though.
In the ApplicationController:
class ApplicationController < ActionController::Base
def nilify(p)
p.transform_values!{|v| v.present? ? v : nil }
end
end
In your controller, modify the strong parameters filter method to call nilify:
class UserController < ApplicationController
def user_params
nilify params.require(:user).permit(:email, :name)
end
end
Chris,
Here is a recursive parsing of params that have blanc values.
before_filter :process_params
......
private
def process_params
....
set_blanc_values_to_nil(params)
end
# Maybe move method to ApplicationController
# recursively sets all blanc values to nil
def set_blanc_values_to_nil!(my_hash)
my_hash.keys.each do |key|
val = my_hash[key]
next if val.nil?
my_hash[key] = nil if val.is_a?(String) && val.empty?
set_blanc_values_to_nil!(val) if val.is_a? Hash
end
end
Here is how I did it.
def remove_empty_params(param, key)
param[key] = param[key].reject { |c| c.empty? }
end
and call it with
remove_empty_params(params[:shipments], :included_clients)
No need to get super tricky in the model. And this way you can control which params get cleaned up.
params = {
"shipments"=>{
"included_clients" => ["", "4"]
}
}
will turn into
>> params["shipments"]
=> {"included_clients" => ["4"] }
You can use attribute_normalizer gem and use the blank normalizer that will transform empty strings in nil values.