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

时间:2013-07-04 22:09:07

标签: ruby-on-rails ruby-on-rails-3.2 rails-migrations

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 个答案:

答案 0 :(得分:30)

您忘记添加“_id”,如下所示:

add_index :ballots, :user_id

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

t.references :user, index: true

更多信息:add_indexreferences

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