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

How to get parent id from nested id which equals (params[:id])?

How can I list all the

duels
a
challenge
has on the challenge show page?

A challenge doesn't have a
duel_id
, but a
dueler
has a
challenge_id
.

challenges_controller

def show
@challenge = Challenge.find(params[:id])
@correct_user = current_user.challenges.find_by(id: params[:id])
@duel = # How to get any and all duels which have a dueler whose challenge_id is equal to @challenge?
end


challenges/show.html.erb

<% @duel.duelers.each do |dueler| %> # Two duelers per duel. I want to show both duelers on page.
<%= dueler.user.name %> will <%= dueler.challenge.name %>.
<% end %>
<%= @challenge.name %>


rails c

Duel.last
id: 169,
pry(main)> Dueler.last
id: 276,
user_id: 2,
challenge_id: 301,
duel_id: 169,

RSB RSB
Answer

Since duels table doesn't have challenge_id, you can do this to get duels through duelers.

def show
 @challenge = Challenge.find(params[:id])
 @correct_user = current_user.challenges.find_by(id: params[:id])
 @duel = Duel.where(id: @challenge.duelers.pluck(:duel_id).uniq).includes(duelers: :user)
end

And, don't forget to add has_many :duelers in duel model.

Since there can be multiple duels for a challenge, you need to make this change in your view

<% @duel.each do |duel| %>
  <% duel.duelers.each do |dueler| %> # Two duelers per duel. I want to show both duelers on page.
    <%= dueler.user.name %> will <%= @challenge.name %>.
  <% end %>
  <%= @challenge.name %>
<% end %>

Hope that helps!

Comments