【问题标题】:Save empty strings as NULL in the database. AmberFramework / Granite在数据库中将空字符串保存为 NULL。 AmberFramework / 花岗岩
【发布时间】:2020-07-28 01:29:44
【问题描述】:

是否可以强制 Granite 在 DB 中将空字符串保存为 NULL?

我试过这段代码:

before_save :nilify_blanks

def nilify_blanks
  self.to_h.keys.each do |column|
    if self[column].is_a?(String) && self[column].empty?
      self[column] = nil 
    end
  end
end

但是编译器给了我一个错误:

 223 | if self[column].is_a?(String) && self[column].empty?
              ^
Error: undefined method '[]' for Foo

【问题讨论】:

    标签: crystal-lang amber-framework


    【解决方案1】:

    最后我用了一个宏:

    class Pet < Granite::Base
      connection pg
      table pets
    
      column id : Int64, primary: true
      column name : String?
      column breed : String?
      column age : Int32?
      timestamps
        
    
      before_save :nilify_blanks
    
      def nilify_blanks
        {% for column in @type.instance_vars.select { |ivar| ivar.annotation(Granite::Column) } %}
          {% if column.type.id == Union(String | Nil).id %}
            col = self.{{column.name}}
            if col && col.strip.empty?
              self.{{column.name}} = nil
            end
          {% end %}
        {% end %}
      end
        
    end
    

    宏会生成这段代码:

      def nilify_blanks
        col = self.name
        if col && col.strip.empty?
          self.name = nil
        end
    
        col = self.breed
        if col && col.strip.empty?
          self.breed = nil
        end
    
        ...
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 2011-11-04
      相关资源
      最近更新 更多