pitosalas
pitosalas

Reputation: 10862

Iterating over a 3 way join

class Participant
  has_many :cells
end

class Round
  has_many :cells
end

class Question
  has_many :cells
end

class Cell
   belongs_to :participant
   belongs_to :question
   belongs_to :Round
end

a = an instance of Participant, Question or Round
b = an instance of Participant, Question or Round

I would like to write an iteration across all instances of Cell that belong to the indicated a and b. I know that a and b are not instances of the same class, but I don't know ahead of time which one they are.

I guess I could write:

if a.class == Participant && b.class == Question
  Cell.select(participant_id: a.id, question_id: b.id).each do 
  ... and so on

But that is really ugly. I think there must be somehow to use the join method but I haven't been able to figure it out.

Upvotes: 0

Views: 63

Answers (1)

Hauleth
Hauleth

Reputation: 23556

Try:

Cell.where(:"#{a.class.to_s.underscore}_id": a.id, :"#{b.class.to_s.underscore}_id": b.id).each do |cell|
  # your code
end

But I'm pretty sure that there is nicer way.

Upvotes: 2

Related Questions