Rails4 create join tabel no need to add primary key in Migration?

邮差的信 提交于 2019-12-04 04:39:57

问题


I use this command :

 rails g migration CreateJoinTableUserPloy user ploy

And i check the Migration file:

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

There are 2 index is be commented by defualt.

Then i run this command:

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?


回答1:


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.

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 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.

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.



来源:https://stackoverflow.com/questions/20013945/rails4-create-join-tabel-no-need-to-add-primary-key-in-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!