为Active Record中的add_column和add_index添加唯一:true
即使我的应用程序不允许用户键入某个位置,我也希望在数据库中强制执行城市的唯一性。 由于我的Rails应用程序将在city列上搜索,我想在city列上添加一个索引,但是想知道是否重要的是添加唯一:true也在索引上。 这是重复吗? 如果这没有意义,如果你能解释原因我真的很感激。
class CreateLocations < ActiveRecord::Migration def change create_table :locations do |t| t.string :city, unique: true t.string :state t.timestamps end add_index :locations, :city, unique: true end end
据我所知, create_table
块中的unique
选项实际上不受支持且不执行任何操作,请参阅TableDefinition 。 要创建唯一索引,您需要按照现在的方式调用方法add_index
。 请注意,唯一索引既可用于唯一性,也可用于搜索等,无需在同一列上添加两个索引。
使用Rails 4,您可以提供:index param hash参数
class CreateLocations < ActiveRecord::Migration def change create_table :locations do |t| t.string :city, index: { unique: true} t.string :state t.timestamps end end end
您可以在scaffolding中指定唯一索引:
rails generate model Locations city:string:uniq state:string
这将创建Model,Spec,Factory和此迁移:
class CreateLocations < ActiveRecord::Migration def change create_table :locations do |t| t.string :city t.string :state t.timestamps null: false end add_index :locations, :city, unique: true end end
Rails知道它正在做什么 - 不再需要了。