I am just starting ROR and making different tables for the SQLite database and am running into some trouble in relation to automatically generated id's of tables and foreign keys. To create my tables I used the "rails generate scaffold" command followed by the attributes that I needed. I went to the db/migrate directory and looked at what I had just defined. But I don't understand how I am supposed to explicitly reference foreign keys. I'm used to using Oracle so I'd normally do this process in the very first step during creation and be done with it already.
我刚开始使用ROR,并为SQLite数据库创建了不同的表,但由于与自动生成的表和外键的id有关,我遇到了一些麻烦。为了创建表,我使用了“rails生成脚手架”命令,后面跟着我需要的属性。我转到db/migrate目录,查看刚才定义的内容。但是我不明白我应该如何明确地引用外键。我习惯使用Oracle,所以我通常在创建的第一个步骤中就会这样做,并且已经完成了。
For example, I have a users table with some general attributes such as a username, password, etc. I also have an orders table with attributes transactionID (auto generated), userID (I want to this to be an FK), PartNo (FK key from the Products table). What I don't understand is how to use the auto generated key from the Users table and include it as a foreign key in the Orders table.
例如,我有一个用户表,其中包含一些通用属性,如用户名、密码等。我还有一个order表,其中包含属性transactionID(自动生成)、userID(我想让它成为FK)、PartNo (product表中的FK键)。我不明白的是如何使用用户表中的自动生成键,并将它作为外键包含在Orders表中。
Also, I read somewhere else that if I put a line of code such as
此外,我还在其他地方读到,如果我放一行代码,比如
t.integer user_id
in my create_orders.rb file then it would automatically know that this is a foreign key!?
在我create_orders。然后它会自动知道这是一个外键!?
I feel like this is probably really easy and I'm missing something. This is my first time using rails and I thought I got to define the foreign keys straight away via SQL. Any help would be greatly appreciated. If I could figure this out it would save me a lot of time.
我觉得这很容易,我错过了一些东西。这是我第一次使用rails,我认为我应该直接通过SQL定义外键。如有任何帮助,我们将不胜感激。如果我能算出来,就能节省很多时间。
1 个解决方案
#1
3
After you do this, on your Order
model, you'd use a belongs_to :user
to generate the relationship and utilize the foreign key.
这样做之后,在您的订单模型上,您将使用belongs_to:user来生成关系并使用外键。
If you want to be able to go from User
to Order
, you'll likely be a one-to-many, so you'd have to do has_many :orders
on User
.
如果您希望能够从一个用户转到另一个订单,那么很可能是一对多,因此必须对用户执行has_many:orders。
Here is the documentation for associations in Rails. And here is the specific documentation for belongs_to
vs has_one
.
这是Rails中关联的文档。这是belongs_to vs has_one的具体文档。
#1
3
After you do this, on your Order
model, you'd use a belongs_to :user
to generate the relationship and utilize the foreign key.
这样做之后,在您的订单模型上,您将使用belongs_to:user来生成关系并使用外键。
If you want to be able to go from User
to Order
, you'll likely be a one-to-many, so you'd have to do has_many :orders
on User
.
如果您希望能够从一个用户转到另一个订单,那么很可能是一对多,因此必须对用户执行has_many:orders。
Here is the documentation for associations in Rails. And here is the specific documentation for belongs_to
vs has_one
.
这是Rails中关联的文档。这是belongs_to vs has_one的具体文档。