ActiveRecord :: Migration的create_join_table的行为是什么?

Tob*_*obi 9 activerecord ruby-on-rails jointable

我发现了一种在我的Rails应用程序中为HABTM关系生成连接表的好方法.

rails g migration CreateJoinTable table1 table2
Run Code Online (Sandbox Code Playgroud)

这会生成一个ActiveRecord::Migration采用该方法的方法create_join_table

我想知道这个奇妙的神秘方法是做什么的.我猜它会使一个表(可能没有id字段)有一个table1外键列和一个table2外键列,但该表是否还有其他功能?我对连接表的习惯一直是在这两列中添加唯一索引,以便table1中的记录和table2中的记录之间的关系不能输入两次.

我的问题归结为:如果我使用create_join_table,我需要继续添加该唯一索引,或者这种方法是否适合我(我认为它应该)?

我通常看文档并没有涉及这种细节.

Yan*_*lly 5

调用时不带任何块,create_join_table只需创建一个表,该表具有两个引用两个联接表的外键。

但是,实际上,当您调用该方法进行任何其他操作(例如,添加索引)时,您可以传递一个块。从Rails文档中:

create_join_table :products, :categories do |t|
  t.index :product_id
  t.index :category_id
end
Run Code Online (Sandbox Code Playgroud)

看一下create_join_table文档

您可以检查create_join_table底部的代码(单击Source:sh​​ow)。


Tob*_*obi 2

事实证明,它所做的只是我在问题中描述的基础知识。我通过运行迁移并查看最终结果发现了这一点db/schema.rb

对于那些感兴趣的人,要获取唯一索引,请执行以下操作:

class CreateJoinTable < ActiveRecord::Migration
  def change
    create_join_table :posts, :users
    add_index :posts_users, [:post_id, :user_id], unique: true, name: 'index_posts_users'
  end
end
Run Code Online (Sandbox Code Playgroud)