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

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

问题描述

我发现了一种在Rails应用中为我的HABTM关系生成联接表的好方法。

  rails g迁移CreateJoinTable table1 table2 

这将生成 ActiveRecord :: Migration 使用方法 create_join_table



我想知道这种奇妙的神秘方法的作用。我猜它构成一个表(可能没有 id 字段),该表具有一个用于table1外键的列和一个用于table2外键的列,但是该表是否具有其他功能?我联接表的习惯一直是在这两列上都添加唯一索引,这样就不能两次输入table1中的记录和table2中的记录之间的关系。



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

我通常看的文档没有

解决方案

事实证明,它除了我在本文中介绍的基础知识外没有其他用途。问题。我只是通过运行迁移并查看最终结果在 db / schema.rb



中发现了这些要获得唯一索引,请执行以下操作:

  class CreateJoinTable< ActiveRecord :: Migration 
def change
create_join_table:posts,:users
add_index:posts_users,[:post_id,:user_id],唯一:true,名称:'index_posts_users'
结尾
结束


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

rails g migration CreateJoinTable table1 table2

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

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.

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.

解决方案

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天全站免登陆