【问题标题】:Rails: "t.references" not working when creating indexRails:创建索引时“t.references”不起作用
【发布时间】:2013-07-04 22:09:07
【问题描述】:
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 应该为我处理这个问题?

【问题讨论】:

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


    【解决方案1】:

    你忘了像这样添加“_id”:

    add_index :ballots, :user_id
    

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

    t.references :user, index: true
    

    更多信息:add_indexreferences

    HTH

    【讨论】:

    • 啊,好吧。我原以为在 t.references 和 add_index 之间会使用相同的语法,但我想这里不是这样。感谢您提供index: true 的提示;我不知道。
    • 是的,这不是很明显,但是“t.references”通过添加“user_id”列来引用“用户”:)
    • 在 Rails 5 中 t.references :user 默认会创建索引
    【解决方案2】:

    上面的答案是正确的,但请注意:

    t.references :user, index: true 仅适用于Rails 4.0 & up.

    在早期版本的 Rails (3.x) 中,index: true 将静默失败,使您在该表上没有索引。对于 Rails 3.2.x 及以下版本,请使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 2015-04-27
      相关资源
      最近更新 更多