Make blank params[] nil

前端 未结 13 598
半阙折子戏
半阙折子戏 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:47

    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.

    0 讨论(0)
  • 2020-12-13 18:47

    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.

    0 讨论(0)
  • 2020-12-13 18:49

    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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-13 18:50

    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"] }
    
    0 讨论(0)
  • 2020-12-13 18:52

    You can use attribute_normalizer gem and use the blank normalizer that will transform empty strings in nil values.

    0 讨论(0)
提交回复
热议问题