如何在两个模型之间建立两个 has_many/belongs_to 关系? [英] How do I do two has_many/belongs_to relationships between two models?

查看:41
本文介绍了如何在两个模型之间建立两个 has_many/belongs_to 关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Project 模型和一个 Contact 模型.Project 模型有一个所有者和一个客户,两者都是 Contact.我显然有一些模棱两可的事情,因为如果我有一个联系人并询问它的项目,Rails 将不知道我是在询问它的项目是客户所在的地方还是所有者所在的地方.到目前为止,我已经有了这个:

I've got a Project model, and a Contact model. The Project model has an owner and a client, both of which are Contacts. I've obviously got something ambiguous going on, because if I have a contact and ask for its projects, Rails won't know whether I'm asking for it's projects where it's the client or where it's the owner. So far I've got this:

class Contact < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => 'Contact', :foreign_key => 'owner_id'
  belongs_to :client, :class_name => 'Contact', :foreign_key => 'client_id'
end

我如何在这里建立两个关系?

How do I make two relationships here?

推荐答案

它类似于在其他类中定义 belongs_to 的方式.

Its similar to the way belongs_to is defined in the other class.

所以基本上

class Contact < ActiveRecord::Base
  has_many :projects_owned, :class_name => "Project", :foreign_key => "owner_id"
  has_many :projects_as_client, :class_name  => "Project", :foreign_key => "client_id"
end

协会的名称可能会更好.我之前描述的单表继承方法也是一种巧妙的方法,但是如果您对 OwnerContact 和 ClientContact 类中的每个类都有很多不同的行为,请使用它,否则它可能只是无用的开销.

names of associations could be better. The Single Table inheritance approach described before me is also a neat way, but go for it if you have a lot of different behaviour for each of the OwnerContact and ClientContact class, otherwise it might be just a useless overhead.

这篇关于如何在两个模型之间建立两个 has_many/belongs_to 关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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