AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

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,

Upvotes: 0

Views: 125

Answers (1)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

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!

Upvotes: 1

Related Questions