Rails:创建索引时“t.references”不起作用
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
应该为我处理这个问题?
你忘了像这样添加“_id”:
add_index :ballots, :user_id
或者,如果您希望自动编入索引:
t.references :user, index: true
更多信息: add_index , 参考
HTH
上面的答案是正确的,但要注意:
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