Rails: 创建索引时 "t.references" 不起作用

13
class CreateBallots < ActiveRecord::Migration
  def change
    create_table :ballots do |t|
      t.references :user
      t.references :score
      t.references :election
      t.string :key
      t.timestamps
    end
    add_index :ballots, :user
    add_index :ballots, :score
    add_index :ballots, :election
  end
end

结果是:

SQLite3::SQLException: table ballots has no column named user: CREATE  INDEX "index_ballots_on_user" ON "ballots" ("user")/home/muhd/awesomevote/db/migrate/20130624024349_create_ballots.rb:10:in `change'

我以为t.references应该为我处理这个问题?
2个回答

32

您忘记添加 "_id",应该像这样:

add_index :ballots, :user_id

或者,如果您希望它自动索引:

t.references :user, index: true

更多信息:add_indexreferences

希望对你有帮助


噢,好的。我本以为t.references和add_index之间使用相同的语法,但看来情况并非如此。谢谢你提醒我可以使用“index: true”;我之前不知道这个。 - Muhd
是的,这并不是很明显,但是"t.references"通过添加"user_id"列来引用"user" :) - a.s.t.r.o
在Rails 5中,t.references :user默认会创建索引。 - Konstantin Tikhonov

17
上面的答案是正确的,但需要注意: t.references :user, index: true 仅适用于 Rails 4.0及以上版本
在较早的 Rails 版本(3.x)中,index: true 会静默失败,导致该表没有索引。对于 Rails 3.2.x 及以下版本,请使用 旧语法add_index :ballots, :user_id 或者完整地使用您的示例:
class CreateBallots < ActiveRecord::Migration
  def change
    create_table :ballots do |t|
      t.references :user
      t.references :score
      t.references :election
      t.string :key
      t.timestamps
    end
    add_index :ballots, :user_id
    add_index :ballots, :score_id
    add_index :ballots, :election_id
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接