开发者

Adding foreign key after app creation in Rails

What's the proper way of a开发者_StackOverflow社区dding a FK relationship in rails AFTER the tables have been created? I've defined my relationship in my model, but do I have to add the [foreigntable]_id field to the table myself using generate migration? Or is there another option?


You definitly need to create a new migration:

rails g migration add_foreign_key_to_model_name_pluralized foreigntable_id:integer

example:

rails g migration add_foreign_key_to_users profile_id:integer


You need to use a gem like foreigner to add the FK constraint to the Database. The answer by @apneadiving adds a column "profile_id" to the users table. It's a relationship as stated, but not a constraint in the DB. Just thought I'd point that out since I'm doing something similar right now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜