form_with模型更改用于编辑表单的url参数

时间:2019-03-25 03:19:21

标签: ruby-on-rails ruby form-helpers

用于REST的REST路由除了覆盖最后一个URL参数之外,还将覆盖第一个URL参数,但其他参数未更改。

如何阻止表单更改url first参数?

views / rounds / edit.html.erb

<h1>Editing Round</h1>

<%= render 'form', round: @round %>
<%= link_to 'Show', round_path(params[:tid],params[:rid]) , class: 'btn btn-primary'  %> |
<%= link_to 'Back', tournament_path(params[:tid]), class: 'btn btn-primary' %>

views / rounds / _form.html.erb

<%= form_with(model: round, local: true) do |form| %>

  ...

  <div class="actions">
  <%= form.submit ( form.object.new_record? ? "Create" : "Update"), class: 'btn btn-primary'%>
  </div>

<% end %>

config / routes.rb

get "tournaments/:tid/rounds" => "rounds#index", as: 'rounds'
get "tournaments/:tid/rounds/new" => "rounds#new", as: 'new_round'
post "tournaments/:tid/rounds" => "rounds#create"
delete "tournaments/:tid/rounds/:rid" => "rounds#destroy"
patch "tournaments/:tid/rounds/:rid" => "rounds#update"
put "tournaments/:tid/rounds/:rid" => "rounds#update"
get "tournaments/:tid/rounds/:rid" => "rounds#show", as: 'round'
get "tournaments/:tid/rounds/:rid/edit" => "rounds#edit", as: 'edit_round'



get "tournaments/:tid/rounds/:rid/matches/:mid/points" => "points#index", as: 'points'
get "tournaments/:tid/rounds/:rid/matches/:mid/points/new" => "points#new", as: 'new_point'
post "tournaments/:tid/rounds/:rid/matches/:mid/points" => "points#create"
delete "tournaments/:tid/rounds/:rid/matches/:mid/points/:pid" => "points#destroy"
patch "tournaments/:tid/rounds/:rid/matches/:mid/points/:pid" => "points#update"
put "tournaments/:tid/rounds/:rid/matches/:mid/points/:pid" => "points#update"
get "tournaments/:tid/rounds/:rid/matches/:mid/points/:pid" => "points#show", as: 'point'
get "tournaments/:tid/rounds/:rid/matches/:mid/points/:pid/edit" => "points#edit", as: 'edit_point'

http://localhost:3000/tournaments/1/rounds/2/edit 页面表单具有作用:

<form action="/tournaments/2/rounds/2" accept-charset="UTF-8" method="post">

为什么:tid被更新为:rid,以及我如何防止它。

http://localhost:3000/tournaments/1/rounds/2/matches/3/points/10/edit

存在相同的问题,即:tid已更新为与:pid匹配,但所有其他参数均完好无损。

<form action="/tournaments/10/rounds/2/matches/3/points/10" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓">

如何确保编辑页面的路由不会更改URL中的:tid参数

1 个答案:

答案 0 :(得分:0)

删除所有通往比赛,回合,比赛和积分的路线,并使用resources条路线

resources :tournaments do
  resources :rounds do
    resources :matches do
      resources :points
    end
  end
end

然后检查是否有效。