rails5.2迁移难题,创建主键和外键

rur96b6h  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(296)

我不知道我的迁移有什么问题,但是它们不起作用,尝试在类别20180724203015\u create\u categories.rb中的主键的产品上添加外键

class CreateCategories < ActiveRecord::Migration[5.2]
   def change
    create_table :categories, id: false do |t|
      t.string :name
      t.text :description
      t.integer :category_id, primary_key: true, auto_increment: true
      t.timestamps
    end
  end
end

20180724203105\创建\产品.rb

class CreateProducts < ActiveRecord::Migration[5.2]
  def change
    create_table :products do |t|

      t.string :name
      t.references :category_id, foreign_key: true, index: true

      t.timestamps
    end
  end
end

但是,这总是以错误结束,不能添加外键约束

dzhpxtsq

dzhpxtsq1#

rubyonrails支持约定优先于配置的原则。这意味着如果您遵循rails惯例,事情将变得更简单,几乎不需要配置。
在迁移过程中,您决定与rails的一个约定作斗争:数据库的主键存储在 id 列。当你决定不遵守这个约定时,你就不能简单地使用 references 方法,而不告诉rails如何设置数据库。
我的建议是:除非你有非常非常好的理由,否则不要反对rails惯例。它不仅会使这个任务(数据库迁移)变得更复杂,而且还会增加一些其他任务需要更多配置(例如activerecord模型)的风险,或者当您将rails更新到一个新版本时,gems可能会出现问题。
也就是说:更改迁移以使用rails约定:


# 20180724203015_create_categories.rb

class CreateCategories < ActiveRecord::Migration[5.2]
   def change
    create_table :categories do |t| # <- create an `id` column per default
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end

# 20180724203105_create_products.rb

class CreateProducts < ActiveRecord::Migration[5.2]
  def change
    create_table :products do |t|
      t.references :category, foreign_key: true # <- just name the relation

      t.string :name

      t.timestamps
    end
  end
end
nxagd54h

nxagd54h2#

解决方法是删除t.integer:category\u id,并依赖于rails:id列。对于每个表,可以使用@category或@product进行引用,如注解中所述-@category=category.find(params[:id])或category.find(params[:category\u id]),因为我认为这是在routes中引用它的方式。谢谢您。

相关问题