2013-07-04 16 views
12
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 

wyniki:szyn: "t.references" nie działa podczas tworzenia indeksu

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' 

Myślałem t.references miała obsługiwać to dla mnie?

Odpowiedz

27

Zapomniałeś dodać "_id" tak:

add_index :ballots, :user_id 

lub, jeśli chcesz to indeksowany automatycznie:

t.references :user, index: true 

Więcej informacji: add_index, references

HTH

+0

Ach, w porządku. Sądziłem, że ta sama składnia będzie używana między t.references i add_index, ale myślę, że tak nie jest. Dzięki za podpowiedź za zrobienie 'index: true'; Nie wiedziałem o tym. – Muhd

+0

Tak, to nie jest tak oczywiste, ale "t.references" odwołuje się do "użytkownika", dodając kolumnę "user_id" :) –

13

Powyższa odpowiedź jest prawidłowa, ale należy pamiętać, że:

t.references :user, index: true jest dostępna tylko w Rails 4.0 & up.

we wcześniejszych wersjach Rails (3.x), index: true zawiedzie cicho, pozostawiając cię bez indeksu na tej tabeli. Dla Rails 3.2.x & dół, użyj the older syntax:

add_index :ballots, :user_id

lub w całości za pomocą przykładu:

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 
Powiązane problemy