简体   繁体   中英

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,

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM