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
应该为我处理这个问题?
答案 0 :(得分:30)
您忘记添加“_id”,如下所示:
add_index :ballots, :user_id
或者,如果您希望自动编入索引:
t.references :user, index: true
更多信息:add_index,references
HTH
答案 1 :(得分:14)
上面的答案是正确的,但请注意:
t.references :user, index: true
仅适用于Rails 4.0 & up.
在早期版本的Rails(3.x)中,index: true
将以静默方式失败,使您在该表上没有索引。对于Rails 3.2.x&amp;向下,使用the older syntax:
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