在数据库中将空字符串保存为 NULL。 AmberFramework / 花岗岩

Save empty strings as NULL in the database. AmberFramework / Granite

是否可以强制 Granite 在数据库中将空字符串保存为 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

终于用上了一个宏:

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