0

What is the correct way to describe the relationship between a User and the Outcomes of their Questions and Contacts? I want to be able to call User.outcomes and get all outcomes for the user, regardless of whether the outcome was for a question or a contact.

Here are my models as they stand right now. Are the has_many through relationships described correctly?

User Model

has_many :questions
has_many :contacts
has_many :outcomes, through: :questions
has_many :outcomes, through: :contacts

Question Model

has_many :outcomes

Contact Model

has_many :outcomes

Outcomes Model

belongs_to :question
belongs_to :contact
kwh941
  • 235
  • 2
  • 9

1 Answers1

1

So, this is probably not the ideal solution because it returns an Array instead of an ActiveRecord::Relation. That means you lose lazy loading and the ability to further add scopes and where statements and whatnot. It's better than writing SQL and should do what you want though:

class User < ActiveRecord::Base

  has_many :questions
  has_many :contacts
  has_many :questions_outcomes, :through => :questions, :class_name => "Outcomes"
  has_many :contacts_outcomes, :through => :contacts, :class_name => "Outcomes"

  def outcomes
    return questions_outcomes + contacts_outcomes
  end
end

Please let us know if you come up with something nicer.

vpsz
  • 457
  • 3
  • 6