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ましたか?

4

2 に答える 2

32

次のように「_id」を追加するのを忘れました:

add_index :ballots, :user_id

または、自動的にインデックスを作成する場合:

t.references :user, index: true

詳細: add_index参照

HTH

于 2013-07-04T22:13:43.150 に答える
15

上記の答えは正しいですが、次のことに注意してください。

t.references :user, index: trueRails 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
于 2014-10-14T23:43:12.417 に答える