【问题标题】:Rails: Edit form sends to post route instead of patchRails:编辑表单发送到发布路线而不是补丁
【发布时间】:2021-05-10 20:17:15
【问题描述】:

在我提交我的编辑表单后,它会路由到 [POST] "/users/1/moves/1/inventory_lists/2" 而不是我的路线: user_move_inventory_list_path
补丁
/users/:user_id/moves/:move_id/inventory_lists/:id(.:format)
inventory_lists#update

<%= form_for(@list, url: user_move_inventory_list_url(@user, @move), method: :patch) do |f| %>
<h3>Edit your list by updating Items</h3>
<p>Any items not in your inventory list will incure additional fees</p>
<% @list.items.each do |item| %>
    <%= f.fields_for item, Item.find_by(id: item.id) do |item_attributes| %>
        <div>
            <%= item_attributes.label :name, "Item Name:"%>
            <%= item_attributes.text_field :name, 'name' => "inventory_list[][item][name]" %>
        </div>
        <div>
            <%= item_attributes.label :room, "Room Item Belongs to:" %>
            <%= item_attributes.text_field :room, 'name' => "inventory_list[][item][room]" %>
        </div>
        <div>
            <%= item_attributes.label :weight, "Item Weight:" %>
            <%= item_attributes.number_field :weight, 'name' => "inventory_list[][item][weight]" %>
        </div>
        <br><br>
    <% end %>
<% end %>

<h3>Add Items</h3>
<div id="row1" class="row">
        <%= f.fields_for :item, Item.new do |item_attributes| %>
                <div>
                    <%= item_attributes.label :name, "Item Name:" %>
                    <%= item_attributes.text_field :name %>
                </div>
                <div>
                    <%= item_attributes.label :room, "Room Item Belongs to:" %>
                    <%= item_attributes.text_field :room %>
                </div>
                <div>
                    <%= item_attributes.label :weight, "Item Weight:" %>
                    <%= item_attributes.number_field :weight %>
                </div>
        <% end %>
</div>
<div>
    <input type="button" id="btnAdd" value="Add Another Item" />
    <input type="button" id="btnDel" value="Remove Item" />
</div>


<%= f.submit 'Update List' %>

【问题讨论】:

  • 我将 config.middleware.use(Rack::MethodOverride) 添加到 ~/config/application.rb 但这似乎也不起作用

标签: ruby-on-rails rest restful-url


【解决方案1】:

嘿——我可以在这里看到的一件事是你有user_move_inventory_list_url,而不是更可取的user_move_inventory_list_path,尤其是对于内部用例。这可能是您的问题的根源。

您几乎应该始终使用_path 变体,除非您为外部用例提供链接,可能是从共享的 twitter URL 或您通过邮件发送的时事通讯 URL 等对您网站上的页面的引用。

Rails 应该自动包含一个隐藏的 html 字段以覆盖 HTTP 方法。

您可以在此处阅读更多内容:https://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-patch-put-or-delete-methods-work-questionmark

【讨论】:

  • 嘿,我尝试使用 _path,但它似乎不起作用。
  • &lt;form class="edit_inventory_list" id="edit_inventory_list_2" action="/users/1/moves/1/inventory_lists/2" accept-charset="UTF-8" method="post"&gt;&lt;input type="hidden" name="_method" value="patch"&gt;
猜你喜欢
  • 1970-01-01
  • 2018-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
相关资源
最近更新 更多