扶手:在数据库中强制空字符串为NULL扶手、数据库中、空字符串、NULL

2023-09-09 22:00:45 作者:梦醒心未醒

有没有一种简单的方法(即配置)强制ActiveRecord的保存空字符串为NULL的DB(如果列允许的话)?

Is there an easy way (i.e. a configuration) to force ActiveRecord to save empty strings as NULL in the DB (if the column allows)?

这样做的理由是,如果你在数据库可为空字符串列没有默认值,新记录不设置这个值将包含空值,而新的记录,这个值设置为空字符串不会NULL,从而导致数据库中的不一致,我想避免的。

The reason for this is that if you have a NULLable string column in the DB without a default value, new records that do not set this value will contain NULL, whereas new records that set this value to the empty string will not be NULL, leading to inconsistencies in the database that I'd like to avoid.

现在我在做我的模特像这样的事情:

Right now I'm doing stuff like this in my models:

before_save :set_nil

def set_nil
  [:foo, :bar].each do |att|
    self[att] = nil if self[att].blank?
  end
end

这工作,但效率不高或干燥。我可以考虑此因素伸到一个方法,它混入ActiveRecord的,但在此之前我走这条路,我想知道是否有一种方法已经做到这一点。

which works but isn't very efficient or DRY. I could factor this out into a method and mix it into ActiveRecord, but before I go down that route, I'd like to know if there's a way to do this already.

推荐答案

尝试,如果这种宝石作品:

Try if this gem works:

https://github.com/rubiety/nilify_blanks