向 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所属企业,属于用户
)和(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方法时不要在词尾使用s
:business_hoursbelongs_to business哪个属于用户
.
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屋!