michaelminter
7/30/2019 - 5:12 PM

Scope messages by two users (Arel)

scope :by_persons, ->(person1, person2) do
  arel = Communication.arel_table
  up_context1 = arel.grouping(arel[:sender_type].eq(person1.class.name).and(arel[:sender_id].eq(person1.id)))
  dn_context1 = arel.grouping(arel[:sender_type].eq(person2.class.name).and(arel[:sender_id].eq(person2.id)))
  up_context2 = arel.grouping(arel[:recipient_type].eq(person1.class.name).and(arel[:recipient_id].eq(person1.id)))
  dn_context2 = arel.grouping(arel[:recipient_type].eq(person2.class.name).and(arel[:recipient_id].eq(person2.id)))

  context1 = arel.grouping(up_context1.or(dn_context1))
  context2 = arel.grouping(up_context2.or(dn_context2))

  where(context1.and(context2))
end