如何修复销毁功能中的“未定义方法”错误

时间:2019-08-23 22:27:33

标签: ruby-on-rails activerecord erb

我正在创建一个页面,登录的用户可以在该页面上查看即将到来的预订列表,并在需要时取消预订。

我已经尝试过使用它作为destroy函数:

def destroy
    @trip = Reservation.find(params[:id])
    @trip.destroy

    flash[:alert] = "This booking has been cancelled."
    redirect_to your_trips_path 
  end  # destroy/ cancel a booking

会产生以下错误

undefined method `space_reservation' for #<#<Class:0x00007f8198a191d8>:0x00007f8195341160>
Did you mean?  space_reservations_url

这是控制器中的相关代码。rb

class ReservationsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_reservation, only: [:approve, :decline, :destroy]

...

 def your_trips
    @today = DateTime.now
    @trips = current_user.reservations.order(start_date: :desc)
  end

 def destroy
    @reservation = Reservation.find(params[:id])
    @reservation.destroy

    flash[:alert] = "This booking has been cancelled."
    redirect_to your_trips_path 
  end  # destroy/ cancel a booking

Routes.rb

 resources :spaces, except: [:edit] do
    member do
      get 'listing'
      delete :delete_image_attachment
      get 'preload'
      get 'preview'
      get 'get_dates'
      get 'get_times'
      put :deactivate
      put :activate
      get 'browse_spaces'
    end
      resources :reservations, only: [:create]
      resources :calendars
  end

  resources :reservations, only: [:approve, :decline, :destroy] do
    member do
      post '/approve' => "reservations#approve"
      post '/decline' => "reservations#decline"
      delete 'destroy'
    end
  end

查看

<div class="panel-body">

        <% @trips.each do |trip| %>
...          
            <div class="col-md-3 text-right trips-index">
              <% if trip.start_date && trip.end_date > @today %>
              <%= link_to 'Cancel', 
                          space_reservation(trip), 
                          method: :delete, 
                          class:"btn btn-danger",
                          data: { confirm: 'Are you sure?' } %> 
              <% end %>
            </div>
          </div>
          <hr/>
        <% end %>
      </div>

我希望单击“取消”按钮时删除预订,并且不再显示在预订列表中。有人发现我在功能上做错了吗?谢谢。

1 个答案:

答案 0 :(得分:0)

错误消息表明space_reservation方法未定义。

在您看来,您在此处调用了该未定义的方法:

<%= link_to 'Cancel', 
  space_reservation(trip), 
  method: :delete, 
  class:"btn btn-danger",
  data: { confirm: 'Are you sure?' } %> 
<% end %>

假定其他所有方法都可以,如果您创建space_reservation方法或找到另一种解决问题的方法,那么它应该可以工作。