mysql - rails : Force empty string to NULL in the database

标签 mysql ruby-on-rails activerecord ruby-on-rails-3.1

是否有一种简单的方法(即配置)来强制 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/

相关文章:

MySQL 查询 - 选择邮政编码匹配

mysql - 带左连接的sql最小值

ruby-on-rails - Ruby Regexp#match with capture 返回 String 而不是 MatchData

php - Codeigniter 正确的 JOIN 请求

java - 类型不匹配 : cannot convert from element type Object to String

Mysql/Mariadb查询在查询数据时动态地将行转换为列

ruby-on-rails - 为什么我在部署时出现 Paperclip::CommandNotFoundError 而不是在我的本地?

mysql - 无法打开 Rails 控制台:未配置生产数据库,建立连接引发 ActiveRecord::AdapterNotSpecified

ruby-on-rails - 这个模型应该如何设计?

ruby-on-rails - 如何逃脱? (问号)运算符在 Rails 中查询 Postgresql JSONB 类型