Rails: “t.references” not working when creating index

江枫思渺然 提交于 2019-12-18 05:46:35

问题


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

results in:

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'

I thought t.references was supposed to handle that for me?


回答1:


You forgot to add "_id" like this:

add_index :ballots, :user_id

or, if you want it indexed automatically:

t.references :user, index: true

More info: add_index , references

HTH




回答2:


The answer above is correct, but be aware that:

t.references :user, index: true is only available in Rails 4.0 & up.

In earlier versions of Rails (3.x), index: true will fail silently, leaving you without an index on that table. For Rails 3.2.x & down, use the older syntax:

add_index :ballots, :user_id

Or in full using your example:

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


来源:https://stackoverflow.com/questions/17478669/rails-t-references-not-working-when-creating-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!