Search code examples
ruby-on-railsrestrestful-url

Rails: Edit form sends to post route instead of patch


After I submit my edit form it routes to [POST] "/users/1/moves/1/inventory_lists/2" Instead of my route: user_move_inventory_list_path
PATCH
/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' %>

<% end %>


Solution

  • Hey – one thing I can see here is that you have user_move_inventory_list_url instead of the more advisable user_move_inventory_list_path especially for internal use cases. This is likely where your issue stems from.

    You should almost always use the _path variant unless you are providing links for external use cases, maybe a reference to a page on your website from a shared twitter URL, or a newsletter URL you are sending via mail, etc.

    Rails should automatically be including a hidden html field to override the HTTP method.

    You can read some more here: https://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-patch-put-or-delete-methods-work-questionmark