Ошибка маршрутизации Rails: маршрут не соответствует [DELETE]

Я новичок в ruby ​​on rails, у меня возникли проблемы с удалением ресурса с помощью form_for.

Я пытаюсь создать список пожеланий для продуктов, где пользователи могут добавлять в свой список несколько экземпляров одного и того же продукта. Вместо создания уникальной записи в базе данных для каждого продукта в списке (независимо от того, есть ли этот продукт уже в списке), я включил столбец счетчика, «строку», который увеличивается по мере того, как пользователь добавляет кратное количество товаров. тот же продукт в свой список пожеланий. По той же логике я хочу, чтобы действие удаления сначала уменьшало этот счетчик, пока он не достигнет 0, а затем удаляло элемент из базы данных.

Вот что у меня есть:

Сообщение об ошибке:

 No route matches [DELETE] "/wish"
 Routes

 Routes match in priority from top to bottom

 wishes_path        GET     /wishes(.:format)           wishes#index
                    POST    /wishes(.:format)           wishes#create 
 new_wish_path      GET     /wishes/new(.:format)       wishes#new
 edit_wish_path     GET     /wishes/:id/edit(.:format)  wishes#edit
 wish_path          GET     /wishes/:id(.:format)       wishes#show
                    PATCH   /wishes/:id(.:format)       wishes#update
                    PUT     /wishes/:id(.:format)       wishes#update
                    DELETE  /wishes/:id(.:format)       wishes#destroy

пожелания/index.html.erb

<div class="wishes_body">
  <h2>Your Wish-List</h2>

  <table>
    <thead>
      <tr>
        <th class="field-label col-md-2 active">
          <label>Name</label>
        </th>
        <th class="col-md-3">Description</th>
        <th class="col-md-1">Amount</th>
        <th class="col-md-1">Number</th>
        <th class="col-md-2">Total</th>
        <th colspan="3" class="col-md-3">Remove</th>
      </tr>
    </thead>

    <tbody>
        <% @wishes.all.each do |w| %>
            <%= render partial: 'wish', object: w %>
        <% end %>
    </tbody>
  </table>
</div>

_wish.html.erb

<tr>
  <td class="field-label col-md-2 active">
    <label><%= wish.product.name %></label>
  </td>
  <td class="col-md-3"><%= wish.product.description %></td>
  <td class="col-md-1"><%= '%.2f' % (wish.product.amount/100.00) %></td>
  <td class="col-md-1"><%= wish.total %></td>
  <td class="col-md-2"><%= '%.2f' % ((wish.product.amount/100.00) * wish.total) %></td>
  <%= form for(wish_path(wish), :html => { method: 'delete' }) do %>
    <td><%= f.label(:i, "How many:") %></td>
    <td><%= f.number_field(:i) %></td>
    <td><%= f.submit :value => "Remove" %></td>
  <% end %>
</tr>

controllers/wishes.controller.rb

class WishesController < ApplicationController

    def index
        @wishes = Wish.where("user_id = ?", "#{current_user.id}")
    end

    def show
        @user = current_user
        @products = @user.wish_list.products.order("created_at DESC")
    end

    def create
        @product = Product.find(params[:product_id])
        if Wish.where(user_id: "#{current_user.id}", product_id: "#{@product.id}").exists?
            @wish = Wish.where(user_id: "#{current_user.id}", product_id: "#{@product.id}").first
            @wish.total += 1

        else
            @wish = @product.wishes.new
            @wish.user = current_user
            @wish.total = 1
        end
        respond_to do |format|
            if @wish.save
                format.html { redirect_to action: "index", notice: 'You have added <%= @wish.product %> to your wish list.' }
                format.json { render :index, status: :created }
            else
                format.html { redirect_to @product, alert: 'Wish was not created succesfully.' }
                format.json { render json: @wish.errors, status: :unprocessable_entity }
            end
        end
    end

    def destroy
        case i = params[:i]
        when @wish.total > i
            @wish.total -= i
            respond_to do |format|
                format.html { redirect_to action: 'index', notice: 'You removed the item from your wish-list.' }
                format.json { head :no_content }
            end
        when @wish.total == i
            @wish.destroy
            respond_to do |format|
                format.html { redirect_to action: 'index', notice: 'You removed the item from your wish-list.' }
                format.json { head :no_content }
            end
        else
            format.html { redirect_to action: 'index', alert: 'You cannot remove more items than you have on your list.' }
            format.json { head :no_content }
        end

    end
end

config.routes.rb

Rails.application.routes.draw do

  root 'static_pages#index'

  get 'static_pages/about'

  get 'static_pages/contact'

  get 'static_pages/landing_page'

  post 'static_pages/thank_you'

  resources :orders, only: [:index, :show, :new, :create]

  resources :users

  devise_for :users, :controllers => { :registrations => "my_devise/registrations" }, 
                     :path => '', :path_names => {:sign_in => 'login', :sign_out => 'logout', :sign_up => 'register'}

  resources :wishes

  resources :products do
    resources :comments
  end

  resources :payments
end

person Sam Phillips    schedule 22.10.2015    source источник
comment
Вероятно, в вашем вопросе опечатка (должно быть form_for вместо form for).   -  person Marek Lipka    schedule 22.10.2015


Ответы (1)


Вы должны реализовать это, используя form_tag вместо form_for, потому что вы не собираетесь использовать ресурс @wish в своей форме:

<%= form_tag wish_url(wish), method: :delete do %>

и т.п.

person Marek Lipka    schedule 22.10.2015
comment
Сначала я пытался использовать form_tag, и у меня была точно такая же ошибка. - person Sam Phillips; 22.10.2015