0

I'm trying to send a fetch delete request using Rails as API. Here's the destroy method in the controller.

def destroy
  track = Track.find_by(id: params[:id])
  track.destroy
end

I'm creating tracks on what would be an app to create song playlists. In index.js I'm calling the event listener in the render track card function.

const renderTrackCard = (trackObj) => {
    let trackCard = document.createElement('div')
    trackCard.className = 'card'
    trackCard.dataset.id = trackObj.id
    trackCard.innerHTML = `
      <p>${trackObj.title} - ${trackObj.artist} - Genre: ${trackObj.genre} <button class="delete-btn" data-action="delete" id="delete-btn"> X </button></p>
    `
    main().appendChild(trackCard)
    document.querySelector('div').addEventListener('click', removeTrack)
}

Followed then by the remove track function.

function removeTrack() {
    event.preventDefault()
    clearTrackForm()
    let id = event.target.dataset.id 
    fetch(BASE_URL+`/tracks/${id}`, {
        method: "DELETE",
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(event.target.parentElement.remove())
}    

When I click on the delete button, nothing happens. Please advise.

Chakreshwar Sharma
  • 2,571
  • 1
  • 11
  • 35
Norbert
  • 103
  • 1
  • 11
  • Are you getting any hits on `rails` server, if yes then share the logs – Chakreshwar Sharma Nov 09 '20 at 14:51
  • This is what going in my server after calling ```destroy!``` ```Started GET "/tracks" for ::1 at 2020-11-09 09:02:13 -0600 Processing by TracksController#index as */* Track Load (0.3ms) SELECT "tracks".* FROM "tracks" ↳ app/controllers/tracks_controller.rb:6:in `index' [active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Attributes (4.36ms) Completed 200 OK in 9ms (Views: 8.1ms | ActiveRecord: 0.3ms | Allocations: 3716)``` – Norbert Nov 09 '20 at 15:03
  • You are getting the `get` request instead of `delete` – Chakreshwar Sharma Nov 09 '20 at 15:07

1 Answers1

0

First thing, what to you think to call destroy! instead destroy to see the StackTrace and know what are going on to your database?

And to do a request to your server-side you can use AJAX like this one

Spawn
  • 58
  • 5
  • This is what going in my server after calling ```destroy!``` ```Started GET "/tracks" for ::1 at 2020-11-09 09:02:13 -0600 Processing by TracksController#index as */* Track Load (0.3ms) SELECT "tracks".* FROM "tracks" ↳ app/controllers/tracks_controller.rb:6:in `index' [active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Attributes (4.36ms) Completed 200 OK in 9ms (Views: 8.1ms | ActiveRecord: 0.3ms | Allocations: 3716)``` – Norbert Nov 09 '20 at 15:04
  • Look at "started GET", your HTTP verb must be `DELETE` – Spawn Nov 09 '20 at 15:05