- 1 year ago 75
Ruby Question

How to get non_current_user?

How to equal the

to whoever is not the
in the


@duel = @dueler.duel
@current_user = @duel.duelers.find_by(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 Source

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 == ? 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 ==}

Another way to write the above code:

@duelers = @dueler.duel.duelers.to_a
@duelers.reverse! unless @duelers[0].user_id ==
@current_user, @non_current_user = @duelers

Note that, I have assumed there are always a pair of duelers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download