AnthonyGalli.com AnthonyGalli.com - 1 month ago 7
Ruby Question

How to get non_current_user?

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,

Answer

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.

Comments