Merge results from two has_many associations with the same model

Viewed 10870

I have users. Users can poke other users, as well as poke themselves. Each poke is directional, and group pokes don't exist. I want to list all pokes (incoming or outgoing) for a given user, without duplicating self-pokes (which exist as both incoming_ and outgoing_pokes).

Here are my models:

class User < ActiveRecord::Base
  has_many :outgoing_pokes, :class_name => "Poke", :foreign_key => :poker_id
  has_many :incoming_pokes, :class_name => "Poke", :foreign_key => :pokee_id
end

class Poke < ActiveRecord::Base
  belongs_to :poker, :class_name => "User"
  belongs_to :pokee, :class_name => "User"
end

I tried creating a method in the User model to merge the pokes:

def all_pokes
  outgoing_pokes.merge(incoming_pokes)
end

but that returns only the self-pokes (those that are both incoming_ and outgoing_pokes). Ideas? Is there a clean way to do this using associations directly?

Also, in the merged list, it'd be great to have two booleans for each poke to record how they're related to the current user. Something like outgoing and incoming.

2 Answers

Now that Rails 5 has OR queries, there is a very readable solution.

def pokes
  outgoing_pokes.or(incoming_pokes)
end

I left off the all in the method name since it is now returning an ActiveRelation and other methods can be chained.

@user.pokes.where(...).includes(...)
Related