Rails:将数据库中的空字符串强制为NULL [英] Rails: Force empty string to NULL in the database

查看:22
本文介绍了Rails:将数据库中的空字符串强制为NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法(即配置)可以强制 ActiveRecord 在数据库中将空字符串保存为 NULL(如果该列允许)?

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)?

这样做的原因是,如果你在数据库中有一个没有默认值的 NULLable 字符串列,没有设置这个值的新记录将包含 NULL,而将这个值设置为空字符串的新记录将不会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

它有效但不是很有效或 DRY.我可以将其分解为一个方法并将其混合到 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.

推荐答案

试试这个 gem 是否有效:

Try if this gem works:

https://github.com/rubiety/nilify_blanks

提供了一个框架,用于在您宁愿使用 DB NULL 而不是简单的空白字符串的情况下在数据库中将传入的空白值保存为 nil...

Provides a framework for saving incoming blank values as nil in the database in instances where you'd rather use DB NULL than simply a blank string...

在 Rails 中,当从表单中保存模型并且用户未提供值时,数据库中会记录一个空字符串,而不是许多人喜欢的 NULL(混合空格和 NULL 可能会造成混淆).这个插件允许你指定一个属性列表(或所有属性的例外),如果在保存模型之前它们是空白的,这些属性将被转换为 nil.

In Rails when saving a model from a form and values are not provided by the user, an empty string is recorded to the database instead of a NULL as many would prefer (mixing blanks and NULLs can become confusing). This plugin allows you to specify a list of attributes (or exceptions from all the attributes) that will be converted to nil if they are blank before a model is saved.

只有属性响应空白?值为 true 时将转换为 nil.因此,这不适用于值为 0 的整数字段,例如...

Only attributes responding to blank? with a value of true will be converted to nil. Therefore, this does not work with integer fields with the value of 0, for example...

这篇关于Rails:将数据库中的空字符串强制为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆