是否有一种简单的方法(即配置)来强制 ActiveRecord 在数据库中将空字符串保存为 NULL(如果列允许)?
这样做的原因是,如果您在 DB 中有一个 NULLable 字符串列没有默认值,则未设置此值的新记录将包含 NULL,而将此值设置为空字符串的新记录将不会NULL,导致我想避免的数据库不一致。
现在我在我的模型中做这样的事情:
before_save :set_nil
def set_nil
[:foo, :bar].each do |att|
self[att] = nil if self[att].blank?
end
end
有效但不是很有效或干燥。我可以将其分解为一个方法并将其混合到 ActiveRecord 中,但在我走这条路之前,我想知道是否有办法做到这一点。
最佳答案
是的,目前唯一的选择是使用回调。
before_save :normalize_blank_values
def normalize_blank_values
attributes.each do |column, value|
self[column].present? || self[column] = nil
end
end
您可以将代码转换为 mixin,以便轻松地将其包含在多个模型中。
module NormalizeBlankValues
extend ActiveSupport::Concern
included do
before_save :normalize_blank_values
end
def normalize_blank_values
attributes.each do |column, value|
self[column].present? || self[column] = nil
end
end
end
class User
include NormalizeBlankValues
end
或者您可以在 ActiveRecord::Base 中定义它以将其包含在您的所有模型中。
最后,您也可以将它包含在 ActiveRecord::Base 中,但在需要时启用它。
module NormalizeBlankValues
extend ActiveSupport::Concern
def normalize_blank_values
attributes.each do |column, value|
self[column].present? || self[column] = nil
end
end
module ClassMethods
def normalize_blank_values
before_save :normalize_blank_values
end
end
end
ActiveRecord::Base.send(:include, NormalizeBlankValues)
class User
end
class Post
normalize_blank_values
# ...
end
关于mysql - rails : Force empty string to NULL in the database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7202319/