如何从嵌套id中获取父id等于(params [:id])?

时间:2016-10-21 10:15:49

标签: ruby-on-rails ruby

如何在质询显示页面上列出duels challenge {}的所有内容?

挑战没有duel_id,但duelerchallenge_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

挑战/ 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,

1 个答案:

答案 0 :(得分:1)

由于duels表没有challenge_id,因此您可以通过适当的方式进行决斗。

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

并且,不要忘记在has_many :duelers模型中添加duel

由于挑战可能有多个duels,因此您需要在视图中进行此更改

<% @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 %>

希望有所帮助!