ruby 为什么我不能删除我的数据库中的用户与我的视图

6yjfywim  于 2023-04-20  发布在  Ruby
关注(0)|答案(1)|浏览(95)

我无法删除数据库中的用户。我不知道为什么我会收到路由错误...我甚至问了ChatGPT,但这根本没有帮助。
下面是我的代码:
路线:

Rails.application.routes.draw do

  delete 'users/delete_user/:id', to: 'users#delete_user', as: 'delete_user'
  post '/newuser', to: 'users#create_new_user'
  get 'users/userlist'
  get 'users/newuser'
  get 'home/about'
  root 'home#index'
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  # root "articles#index"
end

浏览次数:

<h1>All Users</h1>

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Username</th>
      <th scope="col">Password</th>
      <th scope="col">Email</th>
      <th scope="col"></th>
      <th scope="col"></th>
    </tr>
  </thead>
  <tbody>
    <% @users.each do |user| %>
    <tr>
      <td><%= user.users_id %></td>
      <td><%= user.username %></td>
      <td><%= user.userpw %></td>
      <td><%= user.email %></td>
      <td><%= link_to 'Delete', delete_user_path(user.id), method: :delete, data: { confirm: 'Are you sure?' } %></td>
      <td><%= link_to 'Edit', delete_user_path(user.id), method: :delete, data: { confirm: 'Are you sure?' } %></td>
    </tr>
    <% end%>
  </tbody>
</table>

控制器:

def delete_user
    User.find(params[:id]).destroy
    redirect_to users_userlist_path
  end

这就是错误:
没有路由匹配[GET]“/users/delete_user/27”
(27是我的数据库中用户的ID)

irlmq6kh

irlmq6kh1#

这种尝试在很多方面都是失败的,所以让我来展示一下在Rails 7中是如何做到这一点的:

Rails.application.routes.draw do
  resources :users

  get 'home/about' # wut is this?
  root 'home#index'
end

这将创建正确的idomiatically路由。要销毁一个用户,您可以向成员路径(/users/:id)发送DELETE请求:

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update :destroy]

  # GET /users
  # this is what you're calling "listuser".
  def index
    @users = User.all
  end

  # DELETE /users/:id
  def destroy
    @user.destroy
    redirect_to action: :index
  end

  # ...

  private 

  def set_user
    @user = User.find(params[:id])
  end
end
<h1>All Users</h1>

<table class="table">
  ...
  <tbody>
    <% @users.each do |user| %>
    <tr>
      ...
      <td><%= button_to('Delete', user, method: :delete, data: { turbo_confirm: 'Are you sure?' }) %></td>
      <td><%= link_to('Edit', user) %></td>
    </tr>
    <% end%>
  </tbody>
</table>

当你遵循约定时,你可以只传递一个模型示例给link_tobutton_toform_with,它会自动推断路由。button_to创建一个实际的表单,所以它不依赖于javascript来运行(尽管确认仍然如此)。这里的method选项仍然和以前版本的Rails一样工作。
在Rails 7中,Turbo取代了旧的Rails Unobtrusive Javascript Driver(UJS)。虽然Turbo提供了Rails UJS提供的功能的替代品,但使用的数据属性是data-turbo-methoddata-turbo-confirm

<%= link_to(user, data: { turbo_method: :delete, turbo_confirm: 'Are you sure?' }) %>

相关问题