Reputation: 2866
How to equal the user_id
to whoever is not the current_user
in the duel
?
duelers_controller
@duel = @dueler.duel
@current_user = @duel.duelers.find_by(user_id: current_user.id)
@non_current_user = @duel.duelers.find_by(user_id: # the user in the duel who is not the current_user)
redirect_to duel_path(@duel)
rails c
pry(main)> Dueler.last
id: 248,
user_id: 114, # how to get this dueler?
challenge_id: 410,
duel_id: 155,
pry(main)> Dueler.find(247)
id: 247,
user_id: 2, # current_user
challenge_id: 301,
duel_id: 155,
Upvotes: 0
Views: 44
Reputation: 10754
This should do that, while only firing one query (code can be improved for readability though):
@duelers = @dueler.duel.duelers.to_a # should return Dueler IDs 247, 248
@current_user, @non_current_user = @duelers[0].user_id == current_user.id ? duelers : duelers.reverse
# tip: if you have a `limited` no. of records, you can match current user like this:
# @current_user = @duelers.detect{|d| d.user_id == current_user.id}
Another way to write the above code:
@duelers = @dueler.duel.duelers.to_a
@duelers.reverse! unless @duelers[0].user_id == current_user.id
@current_user, @non_current_user = @duelers
Note that, I have assumed there are always a pair of duelers.
Upvotes: 1
Reputation: 11206
I assume there will only ever be two users to a duel. Here is one way of doing it.
@non_current_user = @duel.duelers.where.not(user_id: current_user.id).first
or you can also do
@non_current_user = (@duel.duelers - [@current_user]).first
edit: now that I look closer at your code, you can just do the following:
@current_user = current_user #you don't have to query for the user again if you already have it stored as current_user
@non_current_user = (@duel.duelers - [@current_user]).first
Upvotes: 1