Reputation: 2195
Two questions here related to the same problem. One is modelled with a polymorphic association, the other with a standard association.
I have a model which can have two paths to the same item.
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
As such Client can
has_many :notes, through: :opportunity
has_many :emails, through: :opportunity
I can't work out how to model the situation where I want all the notes, or all the emails related to a client, regardless of whether they're 'one step removed'.
i.e. I want to do something like
@client.all_emails
and return all emails whether they are directly connected to the client or one of their associated opportunities and
@client.all_notes
and return all notes likewise
I should note that in both cases, the client can often have both notes and emails without a relevant opportunity interceding.
Upvotes: 0
Views: 33
Reputation: 6100
You will have to create method for this, this can not be done using assoications
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
Upvotes: 1