AnthonyGalli.com AnthonyGalli.com - 3 months ago 12
Ruby Question

Get id for nested MVC?

<%= @dueler.id %>
is showing the wrong integer. For example, duel has two duelers
34
and
35
. The
current_user
is
78
, which dueler
34
is user
78
.

By making sure the
current_user
is a dueler of the duel then he will be empowered to update his dueler status.

duels/show

Duel <%= @duel.id %> = 20
Dueler <%= @dueler.id %> = 10 # How to get 34 instead?
User <%= current_user.id %> = 78


rails c

pry(main)> Dueler.last
id: 34, # This is what it should say since 78 is the current_user
user_id: 78,
challenge_id: 295,
duel_id: 20,
accept: nil>
pry(main)> Dueler.last
id: 35,
user_id: 150,
challenge_id: 290,
duel_id: 20,
accept: nil>
pry(main)> Duel.last
id: 20,
consequence: "TEST",
reward: "TEST",
created_at: Fri, 05 Aug 2016 21:38:31 EDT -04:00,
updated_at: Fri, 05 Aug 2016 21:38:31 EDT -04:00>


duels_controller

def show
@duel = Duel.find(params[:id])
@duelers = Duel.duelers.find(params[:id]) # What should this be instead?
end


I thought maybe something like this would work:

def show
@duel = Duel.find(params[:id])
@duelers = Duel.duelers.find(params[:id]) # Get hash of duelers i.e. 34 & 35
@dueler = @duelers.find(current_user = Dueler.user_id) # If current_user is equal to the user_id of dueler then that dueler is thee dueler, i.e. 34
end

Answer

In duels_controller

def show
  @duel = Duel.find(params[:id])  ##params[:id] should be 20
  @dueler = @duel.duelers.find_by(user_id: current_user) ##it will return first dueler of duel which is 34 for the user: 78. in the given example. 
end   

In show method view:

Duel <%= @duel.id %> = 20
Dueler <%= @dueler.id %> = 34 
User <%= current_user.id %> = 78
Comments