Ruby-on-rails 向 rails 模型添加外键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16257116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding foreign key to a rails model
提问by Chris
I'm quite new to rails and have been trying to work this out all night with no luck.
我对 Rails 很陌生,并且整晚都在努力解决这个问题,但没有运气。
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).
我已经创建了3种型号:users,businesses,和business_hours。我还添加了关联 ( business_hours belongs_to businesses which belongs_to users) 和 ( user has_one business which has_many business_hours)。
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.
在线阅读文档似乎我现在需要在我的数据库表中为这些关系创建外键。我如何使用 Rails ActiveRecord 迁移来做到这一点?我使用 PostgreSQL 作为我的数据库。
采纳答案by Danil Speransky
First of all when you use belongs_to method don't use sat the end of the word: business_hours belongs_to business which belongs_to user.
首先,当你使用belongs_to 方法时,不要s在词尾使用: business_hours belongs_to business which belongs_to user。
Now create a migration:
现在创建一个迁移:
rails generate migration migration_name
And in migration add columns:
并在迁移中添加列:
class MigrationName < ActiveRecord::Migration
def change
add_foreign_key :business_hours, :businesses
add_foreign_key :businesses, :users
end
end
Run rake db:migrate. That's it.
运行rake db:migrate。就是这样。
回答by Chris
The currently accepted answer on this isn't really accurate as it doesn't add a database foreign key. It's just adding integer columns.
当前接受的答案并不准确,因为它没有添加数据库外键。它只是添加整数列。
In Rails 4.2.x, the current approach is:
在Rails 4.2.x 中,当前的方法是:
http://guides.rubyonrails.org/active_record_migrations.html#foreign-keys
http://guides.rubyonrails.org/active_record_migrations.html#foreign-keys
Create a migration:
创建迁移:
rails generate migration migration_name
For existing columns, in the migration add the foreign keys like this:
对于现有列,在迁移中添加如下外键:
class MigrationName < ActiveRecord::Migration
def change
add_foreign_key :business_hours, :businesses
add_foreign_key :businesses, :users
end
end
For Rails 4.xor if you're adding a new columnand want it to be a foreign key you can do this, where you probably also want to specify the index as true, but that's not part of the requirement for the foreign key:
对于Rails 4.x或者如果您要添加新列并希望它成为外键,您可以这样做,您可能还希望将索引指定为 true,但这不是外键要求的一部分:
http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-migration
http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-migration
class MigrationName < ActiveRecord::Migration
def change
add_reference :business_hours, :business, index: true, foreign_key: true
add_reference :businesses, :user, index: true, foreign_key: true
end
end
回答by Renra
I haven't tried it with PostgreSQL but at least with MySQL Rails do NOT create foreign keys, I mean not real db-level foreign keys. All they create is an integer that is named according to the convention. That means that out of the box you do not get the index on this fake foreign key(for faster lookup) and there is also no db-level referential integrity check. To get that you need to do something like:
我没有用 PostgreSQL 试过,但至少用 MySQL Rails 不创建外键,我的意思是不是真正的数据库级外键。他们创建的只是一个根据约定命名的整数。这意味着开箱即用,您不会获得这个假外键的索引(为了更快的查找),并且也没有数据库级别的参照完整性检查。要做到这一点,您需要执行以下操作:
ALTER TABLE your_table ADD CONSTRAINT fk_whatever_you_want_to_name_it FOREIGN KEY (foreign_key_name) REFERENCES another_table(its_primary_key)
In a Rails migration you can pass this as a string argument to the "execute" function. Adding a "real" foreign key also automatically creates an index. At least for me this was a rather nasty surprise.
在 Rails 迁移中,您可以将其作为字符串参数传递给“执行”函数。添加“真实”外键也会自动创建索引。至少对我来说,这是一个相当令人讨厌的惊喜。
回答by Ben Edwards
Rails 5 now can add foreign key in migrations, see http://devdocs.io/rails~5.0/activerecord/connectionadapters/schemastatements#method-i-add_foreign_key. So
Rails 5 现在可以在迁移中添加外键,请参阅http://devdocs.io/rails~5.0/activerecord/connectionadapters/schemastatements#method-i-add_foreign_key。所以
add_foreign_key :articles, :authors
creates
创造
ALTER TABLE "articles" ADD CONSTRAINT fk_rails_e74ce85cbc FOREIGN KEY ("author_id") REFERENCES "authors" ("id")
If you have a non standard data model you can do.
如果你有一个非标准的数据模型,你可以这样做。
add_foreign_key :articles, :users, column: :author_id, primary_key: "lng_id"
which creates
这创造了
ALTER TABLE "articles" ADD CONSTRAINT fk_rails_58ca3d3a82 FOREIGN KEY ("author_id") REFERENCES "users" ("lng_id")

