扶手:的has_many:通过或has_many_and_belongs_to? [英] Rails: has_many :through or has_many_and_belongs_to?

查看:275
本文介绍了扶手:的has_many:通过或has_many_and_belongs_to?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我想通过另一种模式来链接模型到相同型号的其他实例的实例(即任务1>关系&LT;任务2),并想知道如果我可以使用的has_many:通过此<。 / P>

基本上,关系模型将有额外的信息(type_of_relationship,滞后),所以这将是理想的把它作为一个加盟模式。但是,没有两个车型的加入,只有一个...本身。请问的has_many:通过仍然有效?如果是这样,怎么会加入查表?与Rails惯例你将有两列称为ACTIVITY_ID,这显然不会在数据库中的工作

另外,我可以用has_many_and_belongs_to建立多对多的任务模型和关系模型之间,但我不知道这是否准确地描述了一个关系,应该永远只能连接两个工作模式中的任何一个关系模型(虽然当然任务可能属于一个以上的关系,因此,许多多)。

我的直觉说一起去has_many_and_belongs_to和梳理在模型中的规则,但有没有更好的方式来做到这一点?我转圈圈就这一个!

任何帮助AP preciated。

解决方案

的has_many:通过完美地融入你的情况。我不知道你的模型的细节,但让我们说你有用户,每个用户可以有其他用户作为联系人。您可以按如下模拟这种情况:

 类用户的LT;的ActiveRecord :: Base的
  的has_many:contact_records,:foreign_key =&GT; :owner_id
  的has_many:联系人:通过=&GT; :contact_records,:将class_name =&GT; 用户
结束

类ContactRecord&LT;的ActiveRecord :: Base的
  belongs_to的:老板,:将class_name =&GT; 用户
  belongs_to的:用户
结束
 

I have an app where I want to link an instance of a model to another instance of the same model via another model (i.e. Task1 > Relationship < Task2) and am wondering if I can use has_many :through for this.

Basically, the relationship model would have extra information (type_of_relationship, lag) so it would be ideal to have it as a joining model. However, there are not two models to join, only one … to itself. Would the has_many :through still work? If so, how would the join table look? With Rails conventions you would have two columns called Activity_id, which obviously won’t work in the database.

Alternatively, I can use has_many_and_belongs_to to set up a many-many between the Task model and the Relationship model but I'm not sure if this accurately describes a relationship that should only ever link two Task models in any one Relationship model (although of course the Tasks may belong to more than one Relationship, hence many-many).

My instinct says to go with has_many_and_belongs_to and sort out the rules in the models but is there a better way to do this? I’m going round in circles on this one!

Any help appreciated.

解决方案

has_many :through fits perfectly into your situation. I don't know about specifics of your model, but let's say you have users and every user can have other users as contacts. You can model this situation as follows:

class User < ActiveRecord::Base
  has_many :contact_records, :foreign_key => :owner_id
  has_many :contacts, :through => :contact_records, :class_name => "User"
end

class ContactRecord < ActiveRecord::Base
  belongs_to :owner, :class_name => "User"
  belongs_to :user
end

这篇关于扶手:的has_many:通过或has_many_and_belongs_to?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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