ActiveRecord::Migration 的 create_join_table 的行为是什么? [英] What is the behaviour of create_join_table of ActiveRecord::Migration?

查看:18
本文介绍了ActiveRecord::Migration 的 create_join_table 的行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've discovered a nice way to generate join tables for my HABTM relationships in my Rails app.

rails g migration CreateJoinTable table1 table2

这会生成一个 ActiveRecord::Migration,它使用了 create_join_table

This generates an ActiveRecord::Migration that employs the method create_join_table

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

I'm wondering what this wonderful mysterious method does. I guess it makes a table (probably without an id field) that has a column for table1 foreign key and a column for table2 foreign key, but does the table have any other features?. My habit for join tables has always been to add a unique index across both those columns so that a relationship between a record in table1 and a record in table2 cannot be entered twice.

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

My question boils down to: If I use create_join_table do I need to keep adding that unique index, or does this method do that for me (I think it should)?

我通常查看的文档没有涉及此类细节.>

The documentation I usually look at doesn't go into this sort of detail.

推荐答案

事实证明,除了我在问题中描述的基础知识之外,它并没有做任何更多的事情.我只是通过运行迁移并查看 db/schema.rb

It turns out it doesn't do any more than the basics I described in the question. I found this out simply by running the migration and seeing what ends up in db/schema.rb

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

For those interested, to get the unique index do this:

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

这篇关于ActiveRecord::Migration 的 create_join_table 的行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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