Make blank params[] nil

前端 未结 13 671
半阙折子戏
半阙折子戏 2020-12-13 18:36

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

13条回答
  •  误落风尘
    2020-12-13 18:50

    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
    

提交回复
热议问题