【问题标题】:MySQL + Rails: errno: 150 "Foreign key constraint is incorrectly formed"MySQL + Rails:errno:150“外键约束格式不正确”
【发布时间】:2017-01-05 03:56:04
【问题描述】:

我正在尝试迁移我的 Rails MySQL 数据库,但出现以下错误:

ActiveRecord::StatementInvalid: Mysql2::Error: 无法创建表 development.comments (errno: 150 "外键约束格式不正确"): CREATE TABLE comments (id int AUTO_INCREMENT主键,comment varchar(255),user_id int,post_id int,created_at datetime NOT NULL,updated_at datetime NOT NULL,INDEX index_comments_on_user_id (user_id),INDEX @987653 post_id),约束fk_rails_03de2dc08c 外键 (user_id) 参考users (id) , 约束fk_rails_2fd19c0db7 外键 (post_id) 参考posts (id) ) 引擎=InnoDB

这是我的迁移:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :linkedin_username
      t.string :facebook_username
      t.string :facebook_id
      t.string :profile_image
      t.string :title_image
      t.string :connection
      t.boolean :team
      t.boolean :active
      t.boolean :admin
      t.string :email
      t.string :password_digest

      t.timestamps
    end
  end
end    

class CreateComments < ActiveRecord::Migration[5.0]
  def change
    create_table :comments do |t|
        t.string :comment
        t.references :user, foreign_key: true
        t.references :post, foreign_key: true
      t.timestamps
    end
  end
end

class CreateCategories < ActiveRecord::Migration[5.0]
  def change
    create_table :categories do |t|
        t.string :name
      t.text :description

      t.timestamps null: false
    end
  end
end

class CreatePosts < ActiveRecord::Migration[5.0]
  def change
    create_table :posts do |t|
        t.string :title
      t.string :description
      t.references :category, foreign_key: true
      t.references :user, foreign_key: true
    end
  end
end

如果有人可以在这里给我一个想法,我将非常感激。我一直在谷歌搜索解决方案一段时间,但找不到与 Rails 相关的任何内容。谢谢!

【问题讨论】:

    标签: mysql ruby-on-rails database


    【解决方案1】:

    我刚刚找到了这个问题的答案。我的错误与我的帖子表迁移最后出现的事实有关。我的 cmets 表迁移引用了 post 表 id 父字段。重新生成评论表迁移并删除之前的评论表迁移后,一切正常。

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 2018-12-02
      • 1970-01-01
      • 2021-11-07
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 2018-03-02
      相关资源
      最近更新 更多