Rails 4.倍
当您已经有用户并上传表,并希望在它们之间添加新的关系时。
你所需要做的就是:使用下面的命令生成一个迁移:
rails g migration AddUserToUploads user:references
这将创建一个迁移文件:
class AddUserToUploads < ActiveRecord::Migration
def change
add_reference :uploads, :user, index: true
end
end
然后,使用rake db:migrate运行迁移。
这个迁移会注意到在uploads表中添加一个名为user_id的新列(引用users表中的id列),另外它还会在新列上添加一个索引。
更新[针对Rails 4.2]
Rails can’t be trusted to maintain referential integrity; relational databases come to our rescue here. What that means is that we can add foreign key constraints at the database level itself and ensure that database would reject any operation that violates this set referential integrity. As @infoget commented, Rails 4.2 ships with native support for foreign keys(referential integrity). It's not required but you might want to add foreign key(as it's very useful) to the reference that we created above.
要向现有引用添加外键,请创建一个新的迁移来添加外键:
class AddForeignKeyToUploads < ActiveRecord::Migration
def change
add_foreign_key :uploads, :users
end
end
要使用外键创建一个全新的引用(在Rails 4.2中),使用以下命令生成一个迁移:
rails g migration AddUserToUploads user:references
这将创建一个迁移文件:
class AddUserToUploads < ActiveRecord::Migration
def change
add_reference :uploads, :user, index: true
add_foreign_key :uploads, :users
end
end
这将为uploads表的user_id列添加一个新的外键。键引用用户表中的id列。
注意:这是添加引用之外的操作,因此您仍然需要先创建引用,然后再创建外键(您可以选择在同一个迁移或单独的迁移文件中创建外键)。活动记录只支持单列外键,目前只支持mysql, mysql2和PostgreSQL适配器。不要在sqlite3等其他适配器上尝试这种方法。参考Rails指南:外键。