0
votes

If you execute the destroy action, you will get such an error. URL:http://localhost:3000/listings/test

enter image description here

View

<% @alllistings.all.order(created_at: :desc).each do |listing| %>
        <tbody>
          <tr>
            <th scope="row">
              <%= link_to listing_path(listing) do %>
                <span class="listing-title"><%= listing.listing_title %></span>
              <% end %>
            </th>
            <td>
              <%= link_to "delete",[listing],method: :delete, data: {confirm: "Are you sure?"} if current_user = listing.user %>
            </td>
          </tr>
        </tbody>
  <% end %>

Controller

class ListingsController < ApplicationController
before_action :set_listing, only: [:destroy]
  def index
    @alllistings = current_user.listings
  end
  def destroy
    @listing.destroy

    return reedirect_to listings_path, notice: "削除しました", :status => :moved_permanently
  end

private
  def set_listing
    @listing = Listing.friendly.find(params[:id])
  end
end

Model

class Listing < ApplicationRecord
 validates :listing_title, presence: true

  include FriendlyId
  friendly_id :listing_title

  def should_generate_new_friendly_id?
     listing_title_changed?
  end
end

rails 5 We are using gem 'friendly_id'. We also introduced slug.

Please answer me my question.

1
Please share the association of Listing with other models. - Imran Ahmad
Can you copy and paste full error from console. - Imran Ahmad
You get Foreign Key constraint error. Please add User model file and Listing and User migration files. - Jokūbas Brunonas Pučinskas
btw. the .all.order(created_at: :desc) should be done in your controller index action. Currently that DB call is being done in the View which breaks the MVC pattern. - neongrau

1 Answers

0
votes

Please try to use in your view.

<%= link_to "delete",listing_path(listing), method: :delete, data: {confirm: "Are you sure?"} if current_user = listing.user %>