Почему я не могу уничтожить эту запись Rails? - PullRequest
0 голосов
/ 21 января 2020

Я не могу удалить эту запись о бронировании рельсов из индекса. html .erb страница за всю мою жизнь. Я попробовал несколько вещей, которые я прочитал на этом форуме. Чего мне не хватает в действии уничтожения или в другом месте?

Я получаю этот ответ, когда нажимаю кнопку удаления: ActiveRecord :: RecordNotFound в ReservationsController # show Не удалось найти резервирование с 'id' = 32 (неважно какую запись я удаляю я получаю тот же ответ)

ruby 2.6.3 рельсы 6.0.2

Из журнала:

 ActionView::Template::Error (undefined method `reservation' for #<#<Class:0x00007fa0fcf97028>:0x00007fa0fd25ab98>
22:52:00 web.1     | Did you mean?  reservation_url):
22:52:00 web.1     |     24:                 <td>&nbsp;</td>
22:52:00 web.1     |     25:                 <td><%= link_to 'Show', reservation %></td>
22:52:00 web.1     |     26:                 <td><%= link_to 'Edit', 

edit_reservation_path(reservation) %></td>
22:52:00 web.1     |     27:                 <td><%= link_to 'Delete', reservation(:user), method: :delete, data: { confirm: 'Are you sure?' } %></td>
22:52:00 web.1     |     28:               </tr>
22:52:00 web.1     |     29:             <% end %>
22:52:00 web.1     |     30:           </tbody>
22:52:00 web.1     |   
22:52:00 web.1     | app/views/reservations/index.html.erb:27
22:52:00 web.1     | app/views/reservations/index.html.erb:16
22:52:11 web.1     | Started GET "/reservations" for ::1 at 2020-01-20 22:52:11 -0800
22:52:11 web.1     | Processing by ReservationsController#index as HTML
22:52:11 web.1     |   User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
22:52:12 web.1     |   Rendering reservations/index.html.erb within layouts/application
22:52:12 web.1     |   Reservation Load (0.6ms)  SELECT "reservations".* FROM "reservations" ORDER BY "reservations"."name" ASC
22:52:12 web.1     |   ↳ app/views/reservations/index.html.erb:16
22:52:12 web.1     |   User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
22:52:12 web.1     |   ↳ app/views/reservations/index.html.erb:22
22:52:12 web.1     |   CACHE User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
22:52:12 web.1     |   ↳ app/views/reservations/index.html.erb:22
22:52:12 web.1     |   CACHE User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
22:52:12 web.1     |   ↳ app/views/reservations/index.html.erb:22
22:52:12 web.1     |   Rendered reservations/index.html.erb within layouts/application (Duration: 11.4ms | Allocations: 3355)
22:52:12 web.1     |   Rendered shared/_head.html.erb (Duration: 40.9ms | Allocations: 9570)
22:52:12 web.1     |   Announcement Load (0.4ms)  SELECT "announcements".* FROM "announcements" ORDER BY "announcements"."published_at" DESC LIMIT $1  [["LIMIT", 1]]
22:52:12 web.1     |   ↳ app/helpers/announcements_helper.rb:3:in `unread_announcements'
22:52:12 web.1     |   Rendered shared/_navbar.html.erb (Duration: 5.3ms | Allocations: 1883)
22:52:12 web.1     |   Rendered shared/_notices.html.erb (Duration: 0.9ms | Allocations: 160)
22:52:12 web.1     |   Rendered shared/_footer.html.erb (Duration: 1.4ms | Allocations: 195)
22:52:12 web.1     | Completed 200 OK in 73ms (Views: 66.5ms | ActiveRecord: 1.9ms | Allocations: 19335)
22:52:12 web.1     | 
22:52:12 web.1     | 
22:52:44 web.1     | Started DELETE "/reservations/32" for ::1 at 2020-01-20 22:52:44 -0800
22:52:44 web.1     | Processing by ReservationsController#destroy as HTML
22:52:44 web.1     |   Parameters: {"authenticity_token"=>"wT/O32OAbcNAGumgXNuM7fz2pEpZuUSaXd4FTQFYp1mn9GKFZxu2tDw5AtOUpC4Izx0eJplYCZJSOmt024tqog==", "id"=>"32"}
22:52:44 web.1     |   Reservation Load (0.5ms)  SELECT "reservations".* FROM "reservations" WHERE "reservations"."id" = $1 LIMIT $2  [["id", 32], ["LIMIT", 1]]
22:52:44 web.1     |   ↳ app/controllers/reservations_controller.rb:52:in `set_reservation'
22:52:44 web.1     |   User Load (5.7ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
22:52:44 web.1     |    (0.3ms)  BEGIN
22:52:44 web.1     |   ↳ app/controllers/reservations_controller.rb:43:in `destroy'
22:52:44 web.1     |   Reservation Destroy (13.7ms)  DELETE FROM "reservations" WHERE "reservations"."id" = $1  [["id", 32]]
22:52:44 web.1     |   ↳ app/controllers/reservations_controller.rb:43:in `destroy'
22:52:44 web.1     |    (1.5ms)  COMMIT
22:52:44 web.1     |   ↳ app/controllers/reservations_controller.rb:43:in `destroy'
22:52:44 web.1     | Redirected to http://localhost:5000/reservations/32
22:52:44 web.1     | Completed 302 Found in 36ms (ActiveRecord: 21.7ms | Allocations: 4161)
22:52:44 web.1     | 
22:52:44 web.1     | 
22:52:44 web.1     | Started GET "/reservations/32" for ::1 at 2020-01-20 22:52:44 -0800
22:52:44 web.1     | Processing by ReservationsController#show as HTML
22:52:44 web.1     |   Parameters: {"id"=>"32"}
22:52:44 web.1     |   Reservation Load (0.3ms)  SELECT "reservations".* FROM "reservations" WHERE "reservations"."id" = $1 LIMIT $2  [["id", 32], ["LIMIT", 1]]
22:52:44 web.1     |   ↳ app/controllers/reservations_controller.rb:52:in `set_reservation'
22:52:44 web.1     | Completed 404 Not Found in 3ms (ActiveRecord: 0.3ms | Allocations: 1259)
22:52:44 web.1     | 
22:52:44 web.1     | 
22:52:44 web.1     |   
22:52:44 web.1     | ActiveRecord::RecordNotFound (Couldn't find Reservation with 'id'=32):
22:52:44 web.1     |   
22:52:44 web.1     | app/controllers/reservations_controller.rb:52:in `set_reservation'

booking_controller.rb:

...

class ReservationsController < ApplicationController
  before_action :set_reservation, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!

  def index
    @reservations = Reservation.all
  end

  def show
  end

  def new
    @reservation = Reservation.new
  end

  def edit
  end

  def create
    @reservation = Reservation.new(reservation_params)
    @reservation.user_id = current_user.id if current_user

    respond_to do |format|
      if @reservation.save
        format.html { redirect_to @reservation, notice: 'Your audition time was         successfully created, write this date and time down so you remember!' }
      else
        format.html { render :new }
      end
    end
  end

  def update
    respond_to do |format|
      if @reservation.update(reservation_params)
        format.html { redirect_to @reservation, notice: 'Selection was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @reservation.destroy
    respond_to do |format|
      format.html { redirect_to reservation_url, notice: 'Selection reservation was successfully destroyed.' }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_reservation
      @reservation = Reservation.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def reservation_params
      params.require(:reservation).permit(:name)
    end

    def authenticate_admin!
      authenticate_user!
      redirect_to action: 'new', status: :forbidden unless current_user.admin?

    end
end

...

booking.rb модель

class Reservation < ApplicationRecord
  belongs_to :user
end

user.rb модель:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :masqueradable, :database_authenticatable, :registerable, :recoverable,    :rememberable, :validatable, :omniauthable

  has_person_name

  validates :first_name, length: { minimum: 2 }
  validates :last_name, length: { minimum: 2 }

  has_many :notifications, foreign_key: :recipient_id
  has_many :services
  has_many :reservations
end

файл rout.rb:

   require 'sidekiq/web'

Rails.application.routes.draw do

  resources :products do
    resource :purchase
  end
  resources :auditions
  resources :reservations

  namespace :admin do
    resources :reservations
    resources :products
    resources :auditions
    resources :users

    root to: "users#index"
  end
  get '/reservation', to: 'reservations#new'
  get '/privacy', to: 'home#privacy'
  get '/terms', to: 'home#terms'

    authenticate :user, lambda { |u| u.admin? } do
      mount Sidekiq::Web => '/sidekiq'
    end


  resources :notifications, only: [:index]
  resources :announcements, only: [:index]
  devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
   root to: 'products#index'
  # For details on the DSL available within this file, see     https://guides.rubyonrails.org/routing.html
end

резервирование / индекс. html .erb файл:

<h3>Reservations</h3>

<table>
  <thead>
    <tr>
      <th>Audition Time</th>
      <th>&nbsp;</th>
      <th>&nbsp;</th>
      <th>Person</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @reservations.order(:name).each do |reservation| %>
      <tr>
        <td><%= reservation.name %></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>

        <td><%= reservation.try(:user).try(:first_name) %></td>
        <td><%= reservation.try(:user).try(:last_name) %></td>
        <td>&nbsp;</td>
        <td><%= link_to 'Show', reservation %></td>
        <td><%= link_to 'Edit', edit_reservation_path(reservation) %></td>
        <td><%= link_to 'Delete', reservation, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New reservation', new_reservation_path %>

Ответы [ 3 ]

2 голосов
/ 21 января 2020

По вашему журналу резервирование успешно удалено, но вы пытаетесь просмотреть его после удаления. В вашем destroy методе смените

redirect_to reservation_url

на

redirect_to reservations_url
0 голосов
/ 22 января 2020

При destroy изменении метода URL как упомянутое «@Vitauts Stočka» или пользовательское как root_url.

Журнал:

Запрос на удаление id=32 с последующим перенаправлением на поиск бронирование с id=32

                   |   DELETED SUCCESSFULLY!
22:52:44 web.1     |   ↳ app/controllers/reservations_controller.rb:43:in `destroy'
22:52:44 web.1     | Redirected to http://localhost:5000/reservations/32
...
22:52:44 web.1     | ActiveRecord::RecordNotFound (Couldn't find Reservation with 'id'=32):

0 голосов
/ 21 января 2020

Из журнала видно, что бронь действительно удалена. Проблема в том, что вы перенаправлены на просмотр удаленного бронирования, который больше не существует. Поэтому вы получаете ошибку 404.

В методе уничтожения попробуйте перенаправить на reservations_url (путь индекса) вместо reservation_url.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...