Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql Rails 5.2迁移难题:创建主键和外键_Mysql_Ruby On Rails_Ruby_Devise - Fatal编程技术网

Mysql Rails 5.2迁移难题:创建主键和外键

Mysql Rails 5.2迁移难题:创建主键和外键,mysql,ruby-on-rails,ruby,devise,Mysql,Ruby On Rails,Ruby,Devise,我无法找出我的迁移出了什么问题,但它们无法工作,试图在类别中的主键的产品上添加外键 20180724203015_create_categories.rb class CreateCategories < ActiveRecord::Migration[5.2] def change create_table :categories, id: false do |t| t.string :name t.text :description t

我无法找出我的迁移出了什么问题,但它们无法工作,试图在类别中的主键的产品上添加外键 20180724203015_create_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
class-CreateCategories
20180724203105_create_products.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
class CreateProducts

但是,这总是以错误结束,无法添加外键约束。答案是删除t.integer:category_id,并依赖rails:id列。对于每个表,可以使用@category或@product进行引用,如注释中所述-@category=cateogray.find(params[:id])或category.find(params[:category_id]),因为我相信这就是它在routes中的引用方式。谢谢。

Ruby on Rails支持约定优先于配置原则。这意味着如果您遵循Rails约定,事情会简单得多,几乎不需要配置

在迁移过程中,您决定与Rails的一个约定抗争:数据库的主键存储在
id
列中。当您决定不遵循此约定时,您不能再简单地使用
references
方法,而不告诉Rails如何设置数据库

我的建议是:除非你有非常非常好的理由,否则不要反对Rails的惯例。这不仅会使这个任务(数据库迁移)更加复杂,而且还会增加其他需要更多配置的风险(例如ActiveRecord模型)或者,当您将Rails更新到新版本时,可能会出现问题

也就是说:更改迁移以使用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
#20180724203015_create_categories.rb
类CreateCategories创建|u表:类别不| t |#更多地说明“将不起作用”。我正在尝试将产品添加到网站内的类别中,但是数据库中没有存储任何内容,因为它会给出一条错误消息,说明类别必须存在,我猜想是因为:products表中的category_id仍然为空,我希望它填充我从中创建产品的关联category_id…实际上我想要的全部内容在类别上是主键:category\u id,在产品上是外键:category\u id,这样我就可以关联表了。为什么在
类别上使用
category\u id
作为主键而不是传统的
id
?我不知道如何将表从:id关联到:id,rails是否在ot中创建category\u id她的话是,我如何将表从:id关联到:id,从类别关联到产品?