rails 多对多自连接 [英] rails many to many self join

查看:33
本文介绍了rails 多对多自连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能指出我正确的方向吗:

could some one point me to the right direction:

我尝试为轨道构建一个模型,该模型包含以下内容:

I try to build a model for rails that build up the following:

A 类-id

ClassA 与许多ClassA"有关系(所以它是对自身的引用)

ClassA has a relation to many "ClassA" (so it is a reference to itself)

我正在寻找迁移和模型.

I am searching for the migration and the model.

我不确定正确的连接表是什么(我认为它是一个简单的 2 列表 ClassA_id、ClassARel_ID -> 都指向 ClassA)以及如何构建模型

I a not sure what the correct join table is (I think its a simple 2 columns table ClassA_id, ClassARel_ID -> both point to ClassA) and how to build the model

谢谢!

推荐答案

我会使用类似的东西

class Person < ActiveRecord::Base
   has_many :friendships, :foreign_key => "person_id", 
      :class_name => "Friendship"

   has_many :friends, :through => :friendships
end

class Friendship < ActiveRecord::Base
   belongs_to :person, :foreign_key => "person_id", :class_name => "Person"
   belongs_to :friend, :foreign_key => "friend_id", :class_name => "Person"  
end

表格会像

people: id; name; whatever-you-need    
friendships: id; person_id; friend_id

这篇关于rails 多对多自连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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