2016-08-06 91 views
0

<%= @dueler.id %>顯示錯誤的整數。例如,決鬥有兩個應對者3435current_user78,其應答者34是用戶78獲取嵌套MVC的ID?

通過確保current_user是決鬥的執行者,他將被授權更新他的應聘者狀態。

決鬥/顯示

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

軌道ç

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 

我想,也許小號omething這樣將工作:

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 

回答

2

在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 

在顯示方法視圖:

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

'其中(USER_ID:CURRENT_USER).first'可以寫成'find_by( user_id:current_user)' – spickermann

+1

@spickermann,謝謝。我編輯了我的答案。 –