Rails 5 的基本原理加入 Table 生成的默认值
Rationale of Rails 5 Join Table Generated Defaults
Rails 5 命令 rails g migration create_foo_bar_join_table
生成以下迁移:
class CreateFooBarJoinTable < ActiveRecord::Migration[5.0]
def change
create_join_table :foos, :bars do |t|
# t.index [:foo_id, :bar_id]
# t.index [:bar_id, :foo_id]
end
end
end
为什么生成器用复合键存根两个(双向)索引?还有为什么他们被注释掉了?我对此感到困惑,找不到任何关于这些建议默认值的明确解释。
以上索引是否比以下索引更高效?
...
create_join_table :foos, :bars do |t|
t.index :foo_id
t.index :bar_id
end
...
阅读 has_and_belongs_to_many
上的文档时偶然发现了确切的答案:
It’s also a good idea to add indexes to each of those columns to speed
up the joins process. However, in MySQL it is advised to add a
compound index for both of the columns as MySQL only uses one index
per table during the lookup.
https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many
Rails 5 命令 rails g migration create_foo_bar_join_table
生成以下迁移:
class CreateFooBarJoinTable < ActiveRecord::Migration[5.0]
def change
create_join_table :foos, :bars do |t|
# t.index [:foo_id, :bar_id]
# t.index [:bar_id, :foo_id]
end
end
end
为什么生成器用复合键存根两个(双向)索引?还有为什么他们被注释掉了?我对此感到困惑,找不到任何关于这些建议默认值的明确解释。
以上索引是否比以下索引更高效?
...
create_join_table :foos, :bars do |t|
t.index :foo_id
t.index :bar_id
end
...
阅读 has_and_belongs_to_many
上的文档时偶然发现了确切的答案:
It’s also a good idea to add indexes to each of those columns to speed up the joins process. However, in MySQL it is advised to add a compound index for both of the columns as MySQL only uses one index per table during the lookup.
https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many