Rails 通过两条途径进行关联

Rails association via two routes

这里有两个问题与同一个问题相关。 一个是用多态关联建模的,另一个是用标准关联建模的。

我有一个模型,它可以有两条通往同一项目的路径。

Client
has_many :opportunities
has_many :notes, as: :notable
has_many :emails

Opportunity
has_many :notes, as: :notable
has_many :emails

Note
attr accessible :notable_id, :notable_type
belongs_to :notable

Email
attr_accessible :client_id, :opportunity_id
belongs_to :client
belongs_to :opportunity

如此 客户可以

has_many :notes, through: :opportunity
has_many :emails, through: :opportunity

我不知道如何模拟我想要所有笔记或与客户相关的所有电子邮件的情况,无论它们是否 'one step removed'。

即我想做类似

的事情
@client.all_emails

和 return 所有电子邮件,无论它们是直接连接到客户还是与他们相关的机会之一 和

@client.all_notes

和return所有笔记同样

我应该注意到,在这两种情况下,客户通常可以在没有相关机会介入的情况下同时收到笔记和电子邮件。

您必须为此创建方法,这不能使用关联来完成

class Client < ActiveRecord::Base

  def all_emails
    Email.joins("INNER JOIN client ON clients.id = emails.client_id AND clients.id = ? INNER JOIN opportunity ON opportunities.id = emails.opportunity_id AND opportunities.id IN (?)", id, opportunity_ids)
  end

  # same way for notes
emd