rails not null/unique在迁移中不会触发错误:S
class CreateDeditProjects < ActiveRecord::Migration
def change
create_table :dedit_projects do |t|
t.string :name, :null => false
t.string :uid, :unique => true
t.boolean :status
t.timestamps null: false
end
end
end
空名称不会触发错误。uid 的重复也没有。
这就是我在架构中看到的.db
ActiveRecord::Schema.define(version: 20150410105216) do
create_table "dedit_projects", force: :cascade do |t|
t.string "name", null: false
t.string "uid"
t.boolean "status"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
嗯,我想我需要在某处添加索引?这不应该是自动的吗?
不过不是空问题是假的。
Rails 会自动在 id 和引用上添加索引,也可能在其他类型的索引上添加索引。如果要添加新索引,可以创建迁移:
def change
add_index :dedit_projects, :uid, unique: true
end
您还可以在模型中使用验证validates_uniqueness_of
和validates_presence_of
。虽然我不明白为什么它不能像现在这样工作:)
唯一性是索引的一个属性,因此您需要单独调用add_index
或这样编写
create_table :dedit_projects do |t|
t.string :uid, index: {unique: true}
...
end