Rails4 创建join tabel 不需要在Migration 中添加主键? [英] Rails4 create join tabel no need to add primary key in Migration?

查看:52
本文介绍了Rails4 创建join tabel 不需要在Migration 中添加主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个命令:

 rails g migration CreateJoinTableUserPloy user ploy

然后我检查迁移文件:

    create_join_table :Users, :Posts do |t|
      #t.index [:user_id, :ploy_id]
      #t.index [:ploy_id, :user_id]
    end

有 2 个索引被默认注释.

There are 2 index is be commented by defualt.

然后我运行这个命令:

rake db:migrate

然后我检查我的数据库结构

Then i check my database structure

而且我没有看到主键,是不是意味着连接表不需要在数据库结构中添加索引和主键?

And i not seen primary key, Does it mean that join tabel no need add index and primary key in database structure?

推荐答案

http://meta.serverfault.com/a 一致/1931,我将对此做出回应,即使某些信息在评论线程中.

Consistent with http://meta.serverfault.com/a/1931, I'm going to respond to this as an answer, even though some of the information is in the comment thread.

Rails 生成的连接表中没有主键(即由 create_join_table 创建,它被名称中带有 JoinTable 的迁移使用)并且 Rails 有没有内在的要求.那是因为大多数纯连接表只能通过连接表的 id 访问,在这种情况下,primary_key 是不必要的.当然,您可以根据需要添加和指定主键列.

There is no primary key in a Rails-generated join table (i.e. as created by create_join_table, which is used by migrations with JoinTable in their name) and Rails has no inherent requirement for one. That's because most pure join tables are only accessed by the id's of the joined tables, in which case primary_key is unnecessary. You can, of course, add and designate a primary key column if you wish.

Rails 确实支持多列 primary_keys,尽管有多个 gem 提供这种支持,例如 https://github.com/composite-primary-keys/composite_primary_keys.

Rails does not support multiple column primary_keys, although there are multiple gems that provide that support, such as https://github.com/composite-primary-keys/composite_primary_keys.

此外,根本不需要创建索引.如果您愿意,您可以创建一个,它会加快对记录的访问速度,但需要花费一些额外的时间来创建和更新记录.请参阅https://stackoverflow.com/a/3658980/1008891了解更多相关讨论.

Further, there is no fundamental need to create an index. You can create one if you wish, and it will speed up access to records at the cost of some additional time spent on record creation and update. See https://stackoverflow.com/a/3658980/1008891 for more discussion of this.

这篇关于Rails4 创建join tabel 不需要在Migration 中添加主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆