向Rails模型添加外键 [英] Adding foreign key to a rails model
问题描述
我对Rails还是很陌生,一直试图整夜没有运气.
I'm quite new to rails and have been trying to work this out all night with no luck.
我创建了3个模型:users
,businesses
和business_hours
.我还添加了关联(business_hours belongs_to businesses which belongs_to users
)和(user has_one business which has_many business_hours
).
I have created 3 models: users
, businesses
, and business_hours
. I have also added the associations (business_hours belongs_to businesses which belongs_to users
) and (user has_one business which has_many business_hours
).
在网上阅读文档似乎现在我需要在我的数据库表中为这些关系创建外键.如何使用Rails ActiveRecord迁移来做到这一点?我正在使用PostgreSQL作为数据库.
Reading through the docs online it seems I now need to create the foreign keys for these relationships in my DB tables. How do I do this using Rails ActiveRecord migrations? I'm using PostgreSQL as my DB.
推荐答案
首先,在使用belongs_to方法时,请勿在单词business_hours belongs_to business which belongs_to user
的末尾使用s
.
First of all when you use belongs_to method don't use s
at the end of the word: business_hours belongs_to business which belongs_to user
.
现在创建迁移:
rails generate migration migration_name
并在迁移中添加列:
class MigrationName < ActiveRecord::Migration
def change
add_foreign_key :business_hours, :businesses
add_foreign_key :businesses, :users
end
end
运行rake db:migrate
.就是这样.
这篇关于向Rails模型添加外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!