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
.
The reason your all_pokes
method is returning only self-pokes is because outgoing_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:
def all_pokes
(outgoing_pokes.all + incoming_pokes.all).uniq
end
...or you could write your own query:
def all_pokes
Poke.where('poker_id = ? OR pokee_id = ?', id, id)
end
# in poke.rb
def relation_to_user(user)
if poker_id == user.id
poker_id == pokee_id ? :self : :poker
elsif pokee_id == user.id
:pokee
else
:none
end
end
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(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With