Make blank params[] nil

前端 未结 13 666
半阙折子戏
半阙折子戏 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 19:08

    before_save seems like the wrong location to me, what if you want to use the value before saving. So I overrode the setters instead:

    # include through module or define under active_record
    def self.nil_if_blank(*args)
      args.each do |att|
        define_method att.to_s + '=' do |val|
          val = nil if val.respond_to?(:empty?) && val.empty?
          super(val)
        end
      end
    end
    
    #inside model
    nil_if_blank :attr1, :attr2
    

    Just to be complete I put the following in lib/my_model_extensions.rb

    module MyModelExtensions
      def self.included(base)
        base.class_eval do
          def self.nil_if_blank(*args)
            args.each do |att|
              define_method att.to_s + '=' do |val|
                val = nil if val.respond_to?(:empty?) && val.empty?
                super(val)
              end
            end
          end
        end
      end
    end
    

    and use it like this:

    class MyModel
      include MyModelExtensions
      nil_if_blank :attr1, :attr2
    end
    

提交回复
热议问题