【问题标题】:How do I add a migration for uniqueness on two columns where I lowercase one column?如何在小写一列的两列上添加唯一性迁移?
【发布时间】:2015-12-31 15:52:24
【问题描述】:

我有两列存储字符串,:column_a:column_b

我知道我能做到:

add_index :table, [:column_a, :column_b], unique: true

但是,我需要做到以下几点:

add_index :table, [:column_a, 'lower(column_b)'], unique: true

当我尝试迁移时,这当然会出错。

我收到lower(column_b) 不是列的错误。

我正在使用 PostgreSQL。

老实说,在这一点上,我正在考虑只创建一个名为 column_b_lowercase 的列来作为索引。

【问题讨论】:

  • 好吧,我曾经在 C# 中做过类似的事情,但是因为重音而不是小写。我只是创建了一个not_accent
  • 如果一切都失败了,直接在 SQL 中执行。 Rails 支持迁移中的任意 SQL 语句。
  • @CraigRinger 是的,我决定这样做。

标签: postgresql ruby-on-rails-4 indexing database-migration


【解决方案1】:

我决定只使用 SQL。这是代码。

class AddUniqueIndexingForLowercaseColumn < ActiveRecord::Migration
  def self.up
    execute "CREATE UNIQUE INDEX table_column_a_lowercase_column_b_index ON table(column_a, lower(column_b))"
  end

  def self.down
    remove_index :table, :table_column_a_lowercase_column_b_index
  end
end 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2016-05-20
    • 2013-12-02
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 2020-05-19
    相关资源
    最近更新 更多