简体   繁体   English

Ruby on Rails与数据库关联

[英]Ruby on Rails and database associations

I'm new to the Ruby world, and there is something unclear to me in defining associations between models. 我是Ruby世界的新手,在定义模型之间的关联时我不清楚。 The question is: where is the association saved? 问题是:关联保存在哪里?

For example, if i create a Customer model by executing: 例如,如果我通过执行以下操作创建客户模型:

generate model Customer name:string age:integer

and then i create an Order model 然后我创建一个订单模型

generate model Order description:text quantity:integer

and then i set the association in the following way: 然后我通过以下方式设置关联:

class Customer < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :customer
end

I think here is missing something, for example the foreign key between the two entities. 我认为这里缺少一些东西,例如两个实体之间的外键。 How does it handle the associations created with the keywords "has_many" and "belongs_to" ? 如何处理使用关键字“ has_many”和“ belongs_to”创建的关联?

Thanks 谢谢

Whenever you generate your order, you can do: 每当您生成订单时,您都可以执行以下操作:

generate model Order description:text quantity:integer customer:references

And it will automatically create the foreign key in the migration for you. 并且它将为您自动在迁移中创建外键。 The rails convention is that every row will have a primary key called "id", and the foreign key is the table it is referencing, followed by an underscore, then id. rails约定是,每行将有一个名为“ id”的主键,外键是它所引用的表,后跟一个下划线,然后是id。 So in this case the orders table will have an attribute called "customer_id" 因此,在这种情况下,orders表将具有一个名为“ customer_id”的属性

Since you've already generated yours, you should create a new migration script that adds an integer column called "customer_id" to your orders table. 由于已经生成了自己的脚本,因此应该创建一个新的迁移脚本,该脚本将一个名为“ customer_id”的整数列添加到您的订单表中。

You don't want to modify an existing migration. 不想修改现有的迁移。 Just create a new one that adds the column. 只需创建一个新列即可添加列。

class add_customer_id_to_orders < ActiveRecord::Migration
  def self.up
    add_column :orders, :customer_id, :integer
  end

  def self.down
    remove_column :orders, :customer_id
  end
end

Note: If you've already done something to create data in your database, this is going to result in some null foreign keys, which you'll want to fix, or just delete and create new data. 注意:如果您已经做过一些事情来在数据库中创建数据,这将导致某些空外键,您需要对其进行修复,或者只是删除并创建新数据。

您应该在订单表中添加一个(整数)列,称为“ customer_id”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM