ruby-on-rails 添加索引Ruby on Rails 4.1.4迁移

gmol1639  于 2023-02-26  发布在  Ruby
关注(0)|答案(2)|浏览(218)

我正在RoR中创建一个项目,运行“rake db:migrate”时出现错误:

Mysql2::Error: Key column 'item_id' doesn't exist in table

我不知道我做错了什么:
这是我的项目迁移

class CreateMerchants < ActiveRecord::Migration
   def change
       create_table :merchants do |t|
           t.string     :name,      null: false, limit: 100
           t.string     :address,   null: false, limit: 200

           t.timestamps
       end
   end
 end

我的购买迁移:

class CreatePurchases < ActiveRecord::Migration
  def change
    create_table :purchases do |t|
        t.references    :purchasers,        null: false
        t.references    :items,             null: false
        t.references    :merchants,         null: false
        t.decimal       :purchase_count,    null: false, precision: 17, scale: 2

        t.timestamps
    end

    add_index       :purchases,     :item_id
    add_index       :purchases,     :merchant_id
    add_index       :purchases,     :purchaser_id
  end
end

有人能告诉我哪里错了吗?

j91ykkif

j91ykkif1#

问题是引用需要一个单数名称,您也可以在创建引用的同一行中创建索引,这样您的迁移应该如下所示:

class CreatePurchases < ActiveRecord::Migration
  def change
    create_table :purchases do |t|
        t.references    :purchaser,        null: false, index: true
        t.references    :item,             null: false, index: true
        t.references    :merchant,         null: false, index: true
        t.decimal       :purchase_count,   null: false, precision: 17, scale: 2

        t.timestamps
    end
  end
end
wljmcqd8

wljmcqd82#

试试这个:

class CreatePurchases < ActiveRecord::Migration
  def change
    create_table :purchases do |t|
        t.integer    :purchaser_id,        null: false
        t.integer    :item_id,             null: false
        t.integer    :merchant_id,         null: false
        t.decimal    :purchase_count,      null: false, precision: 17, scale: 2

        t.timestamps
    end

    add_index       :purchases,     :item_id
    add_index       :purchases,     :merchant_id
    add_index       :purchases,     :purchaser_id
  end
end

相关问题