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
.
Now that Rails 5 has
OR
queries, there is a very readable solution.I left off the
all
in the method name since it is now returning an ActiveRelation and other methods can be chained.The reason your
all_pokes
method is returning only self-pokes is becauseoutgoing_pokes
is not an array yet, but an AR relationship that you can chain on.merge
, in this case, combines the queries before executing them.What you want is to actually perform the queries and merge the result sets:
...or you could write your own query:
Determining whether it's incoming or outgoing: