新手问题 Rails Migration 指定唯一索引不起作用 unique: true

lilijreey · 2016年11月14日 · 最后由 colorfulberry 回复于 2016年11月16日 · 3173 次阅读

大家好:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
       ## 这里的unique:true 根本不起作用请问是为什么?
      t.bigint :phone, index:true, unique:true, null:false
    end
  end
end

# 如果这样写就 OK
t.bigint :phone, null:false
t.index :phone, unique: true

# 这样也可以
t.bigint :phone, index:{unique:true}, null:false

Rails.5.1 pg

unique 这个默认会加 index 的。可以查看下数据库的 ddl

#1 楼 @icepoint1999 (⊙o⊙) 这样啊。但是设计的不够正交。

Rails 不支持这种用法的,用下边那种就好了 http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

需要单独 add_index

我曾经用 int 存过手机号,然后所有的号码都变成了 2147483647

😄

往事不堪回首,哈哈。

#5 楼 @xiaoronglv 这是个不应该发生的错误啊

@lilijreey 手机号可是 11 位额,Mysql 中 int 最大 2147483647。 😄 国际化中还要前缀呢 存个 string 就好了吧

需要 登录 后方可回复, 如果你还没有账号请 注册新账号