通过父控制器更新嵌套资源&视图?

时间:2016-08-05 01:40:30

标签: ruby-on-rails ruby model-view-controller error-handling routing

如何更新其父控制器内的嵌套资源&查看?

pry(main)> Duel.last #Duel has_many Duelers
 id: 16,
 consequence: "test",
 reward: "test",
 created_at: Wed, 03 Aug 2016 19:01:46 EDT -04:00,
 updated_at: Wed, 03 Aug 2016 19:01:46 EDT -04:00>
pry(main)> Dueler.last
 id: 26,
 user_id: 78,
 challenge_id: 175,
 created_at: Wed, 03 Aug 2016 19:01:46 EDT -04:00,
 updated_at: Wed, 03 Aug 2016 19:01:46 EDT -04:00,
 duel_id: 16,
 accept: nil>
pry(main)> Dueler.find(25)
 id: 25,
 user_id: 15,
 challenge_id: 192,
 created_at: Wed, 03 Aug 2016 19:01:46 EDT -04:00,
 updated_at: Wed, 03 Aug 2016 19:01:46 EDT -04:00,
 duel_id: 16,
 accept: nil>
[15] pry(main)>

当用户点击submit @dueler时,@dueler应该1)更新,2)重定向回到决斗/节目。

duels_controller.rb

class DuelsController < ApplicationController
  before_action :set_duel, only: [:show, :edit, :update]
  respond_to :html

  def show
    @dueler = Dueler.find_by(user_id: current_user.id)
    respond_with(@duel)
  end

  def create
    @duel = Duel.new(duel_params)
    @duel.save
    redirect_to duel_request_url(@duel)
  end

  private
    def set_duel
      @duel = Duel.find(params[:id])
    end

    def duel_params
      params.require(:duel).permit(:consequence, :reward, duelers_attributes: [:id, :user_id, :challenge_id, :accept])
    end
end

决斗/显示

<% @duel.duelers.each do |dueler| %>
    <%= dueler.user.name %> <%= dueler.user.last_name %> will <%= dueler.challenge.name %>
<% end %>

The loser(s) will <%= @duel.consequence %><br><br>
If everyone succeeds they will <%= @duel.reward %><br><br>

<%= form_for @dueler, :url => { :controller => "duels", :action => "show" }, :html => {:method => :post} do |f| %>
  Accept? <%= f.check_box :accept %>
  <%= f.submit %>
<% end %>

但是在submit我收到了错误:Routing Error No route matches [POST] "/duels/13"。在routes.rb中有resources :duelers resources :duels

1 个答案:

答案 0 :(得分:0)

您希望将方法更改为patch

<%= form_for @dueler, :url => { :controller => "duels", :action => "show" }, :html => {:method => :patch} do |f| %>

如果您查看documentationresources将创建POST路线进行创建。对于更新,使用PATCH方法。