ActiveRecord,"index:true"是什么意思?

011*_*112 17 activerecord ruby-on-rails

我正在编写涉及外键的迁移.看着我的同事代码,我看到他添加了这一行: t.reference :tablename, index: true

t.reference部分是有道理的,但我不知道是什么index: true意思.有人能告诉我吗?我无法在文档中找到它.

注意:这不是重复:Rails ActiveRecord :: Migration index:true和add_index有什么区别?这只是两者的区别,但没有解释他们做了什么.

inf*_*sed 20

index: true向引用的列添加数据库索引.例如,如果创建:products表:

create_table :products do |t|
  t.references :user, index: true
end
Run Code Online (Sandbox Code Playgroud)

这将user_idproducts表格中创建一个列.它还将在user_id列上创建一个非唯一索引,名为index_products_on_user_id.

  • 我也很困惑的是数据库索引是什么.我发现wiki文章[这里](http://en.wikipedia.org/wiki/Database_index)很有帮助. (2认同)
  • 出于某种原因,我不得不做`t.references` 复数才能工作。不知道为什么,`rake db:migrate` 吐出错误并建议我使用 `references` 而不是使用 Rails 5.XX 查看此内容的任何人的参考 - 这也是 `--database=postgresql` 标志在 ` rails new 命令。 (2认同)