2013-07-04 18 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 

kết quả trong:Rails: "t.references" không hoạt động khi tạo index

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ôi nghĩ t.references lẽ ra phải xử lý đó đối với tôi?

Trả lời

27

Bạn quên thêm "_id" như thế này:

add_index :ballots, :user_id 

hoặc, nếu bạn muốn nó được lập chỉ mục tự động:

t.references :user, index: true 

Thông tin thêm: add_index, references

HTH

+0

Ah, được rồi. Tôi đã nghĩ rằng cú pháp tương tự sẽ được sử dụng giữa t.references và add_index, nhưng tôi đoán đó không phải là trường hợp ở đây. Cảm ơn bạn đã thực hiện mẹo 'index: true'; Tôi không biết về điều đó. – Muhd

+0

Có, nó không thực sự rõ ràng nhưng "t.references" tham chiếu đến "người dùng" bằng cách thêm cột "user_id" :) –

13

Câu trả lời ở trên là đúng, nhưng lưu ý rằng:

t.references :user, index: true chỉ có sẵn trong Rails 4.0 & up.

Trong các phiên bản trước đó của Rails (3.x), index: true sẽ thất bại âm thầm, để lại cho bạn mà không có một chỉ mục trên bảng đó. Đối với Rails 3.2.x & xuống, sử dụng the older syntax:

add_index :ballots, :user_id

Hoặc đầy đủ sử dụng ví dụ của bạn:

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