Home > database >  Routing Error No route matches [GET] "/products/1"
Routing Error No route matches [GET] "/products/1"

Time:01-30

I'm practicing with RoR with a CRUD, but when I want delete some product, I got this error (like in the image), I don't know why got this error, someone can help me pleas?

This is my routes.rb

Rails.application.routes.draw do
  
  get '/products', to: 'products#index'
  get '/products/new', to: 'products#new'
  post '/products', to: 'products#create'
  post '/products/:id', to: 'products#shows', as: 'product'
  get '/products/:id/edit', to: 'products#edit', as: 'edit_product'
  patch '/products/:id', to: 'products#update'
  delete '/products/:id', to: 'products#delete'
  # resources :products    
end

This is my products_controller.rb

class ProductsController < ApplicationController
  
  def delete
    @product = Product.find(params[:id])
    @product.destroy
    redirect_to products_path
  end

  private
    def product_params
      params.require(:product).permit(:name, :description, :price)
    end
  
end

And this is my index.html.rb, where I'm listing the products.

<h1>Products list</h1>
<table>
  <tr>
    <thead>
      <th>Name</th>
      <th>Description</th>
      <th>price %></th>
    </thead>
  </tr>
  <% @products.each do |product| %>
    <tr>
      <td><%= product.name %></td>
      <td><%= product.description %></td>
      <td><%= product.price %></td>
      <td>
        <%= link_to "Update", edit_product_path(product) %>
        <%= link_to "Delete", product, method: :delete, data: { confirm: 'Are you sure?' } %>
      </td>
    </tr>
  <% end %>
</table>

CodePudding user response:

Looks like you are using Rails 7 since method: :delete is no longer working without ujs.

So, it leads to GET request and there is really no such route in your config. This issue was discussed in this question and the solution is:

  <%= link_to "Delete", product, data: {  turbo-method: :delete, confirm: 'Are you sure?' } %>

But there is a catch: looks like not all versions of Rails 7 support this behavior. And this will not work inside the form because actual mechanics of changing the method is based on creating a hidden form. There is a discussion in the issue and a hint in the docs: you should use links only for GET requests. For other requests use actual forms or buttons, so button_to will do the job better since it can change method and use confirmation prompt.

CodePudding user response:

I infer that you try to do the show action. If it is the case, the HTML verb is wrong. You are using post instead of get.

The POST verb is most often utilized to create new resources.

The HTTP GET method is used to read (or retrieve) a representation of a resource

  •  Tags:  
  • Related