Make blank params[] nil Make blank params[] nil ruby ruby

Make blank params[] nil


Consider what you're doing here by using filters in the controller to affect how a model behaves when saved or updated. I think a much cleaner method would be a before_save call back in the model or an observer. This way, you're getting the same behavior no matter where the change originates from, whether its via a controller, the console or even when running batch processes.

Example:

class Customer < ActiveRecord::Base  NULL_ATTRS = %w( middle_name )  before_save :nil_if_blank  protected  def nil_if_blank    NULL_ATTRS.each { |attr| self[attr] = nil if self[attr].blank? }  endend

This yields the expected behavior:

>> c = Customer.new=> #<Customer id: nil, first_name: nil, middle_name: nil, last_name: nil>>> c.first_name = "Matt"=> "Matt">> c.middle_name = "" # blank string here=> "">> c.last_name = "Haley"=> "Haley">> c.save=> true>> c.middle_name.nil?=> true>>


If you just want to kill the blanks, you can just do params.delete_if {|k,v| v.blank?}.


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.