使用destroy方法时"Couldn't find user with id"报错

When using the destroy method "Couldn't find user with id" error

我正在制作一个 CRUD 应用程序,除销毁外一切正常。当我在编辑页面中单击删除按钮时,出现以下错误:TravelersController#show 中的 ActiveRecord::RecordNotFound,找不到具有 'id'=14 的 Traveler,已提取源(大约第 22 行):

def show
    @traveler = Traveler.find(params[:id])
end

但是,如果我返回我的用户列表,应用程序确实会删除该用户,即使我收到该错误。

这是我的控制器代码:

  def show
    @traveler = Traveler.find(params[:id])
  end

  def destroy
    Traveler.destroy(params[:id])
    redirect_to traveler_path
  end

还有我的编辑页面:

   <%= form_for @traveler do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name %>

      <%= f.label :age %>
      <%= f.number_field :age %></br>

      <%= f.submit %>
    <% end %>
    <%= button_to "DELETE", traveler_path(@traveler), :method => :delete %>

这是因为当您销毁旅行者时,您会重定向到 traveler_path,这是针对 您刚刚删除的旅行者show 操作。它正在尝试加载那个旅行者但失败了。

要解决此问题,只需将其更改为重定向到其他地方 - 例如,旅行者索引路径。