【问题标题】:How to force rails to store empty strings?如何强制rails存储空字符串?
【发布时间】:2013-07-17 16:46:05
【问题描述】:

我问的是 question to force empty strings to be NULL 的反面;相反,我希望将空字符串字段存储为空字符串。我想这样做的原因(即使与to what some people say 相矛盾)是我希望对适用于多种数据库类型(postgres、mysql 等)的表有一个部分唯一性约束,如in this question here 所述。

架构的伪代码基本上是:

Person {
  first_name : String, presence: true
  middle_name : String, presence: true
  last_name : String, presence: true
  birth_date : String, presence: true
  city_of_birth: String, presence: true
  active: tinyint
}

约束是,如果一个人是活跃的,就必须是唯一的;不活跃的人可以不是唯一的(即,我可以有多个不活跃的 John Smith,但只有一个活跃的 John Smith)。

更复杂的是:根据项目规范,用户只需要输入first_name和last_name,其他字段都可以为空。

我们当前应用部分唯一性约束的解决方案是使用 NULL != NULL 的事实,如果有人不活动,则将活动 tinyint 设置为 NULL,如果有人活动,则将其设置为 1。因此,我们可以在迁移中使用这个 rails 代码:

add_index :Persons, [first_name, middle_name, last_name, birth_date, 
  city_of_birth, active], unique:true, name: "unique_person_constraint"

但是,为了使此约束起作用,其他字段都不能为 NULL。如果是,那么两个没有其他填充字段且 active = 1 的 John Smiths 仍将是“唯一的”,因为值为 NULL 的 middle_name 字段将彼此不同(因为 NULL != NULL,无论列类型如何)。

但是,当我这样做时

options = { first_name: "John",
  middle_name: "", 
  last_name: "Smith",
  birth_date: "",
  city_of_birth: "",
}
person = Person.new(options)
success = person.valid?

success 总是假的,因为

Middle name can't be blank
City of birth can't be blank
Birth date can't be blank

所以我需要一种方法来确保我始终为那些其他字段至少有空字符串,以强制执行部分唯一性约束。我怎样才能做到这一点?如果我去掉模型定义中的 presence:true,那么现在似乎允许 NULL 字段,这很糟糕。

这是Rails 3.2.13,如果需要我可以提供其他gem和gem版本。

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    除了存在 true,您还可以将 allow_blank 添加为 true,这将允许您保存空字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      相关资源
      最近更新 更多