【问题标题】:Get id for nested MVC?获取嵌套 MVC 的 id?
【发布时间】:2016-08-06 04:23:08
【问题描述】:

<%= @dueler.id %> 显示错误的整数。例如,决斗有两个决斗者3435current_user78,其中决斗者34是用户78

通过确保current_user 是决斗的决斗者,那么他将有权更新他的决斗者状态。

决斗/表演

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

轨道 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   

我想也许这样的事情会起作用:

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   

【问题讨论】:

    标签: ruby-on-rails ruby model-view-controller controller nested


    【解决方案1】:

    在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
    

    【讨论】:

    • where(user_id: current_user).first可以写成find_by(user_id: current_user)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2023-03-21
    相关资源
    最近更新 更多